python3,Django验证码生成方法

记得很久以前有尝试过python2.7, Django生成验证码。可以参考以前的文章:
http://www.yihaomen.com/article/python/217.htm(python pil 验证码,汉字验证码)
http://www.yihaomen.com/article/python/573.htm(python/django生成动态验证码, 动态刷新, 直接修改 img src 属性)

那么在python3中,如果还是按照上面的方法去做,肯定是报错的了,因为python3去掉了 cStringIO.StringIO。那么应该采用什么样的办法呢, 下面贴出一个python3下面生成验证码的工具类
程序代码 程序代码

#coding:utf-8
'''
Created on 2017年8月22日
@author: Administrator
'''

from PIL import Image,ImageDraw, ImageFont, ImageFilter
import random
_letter_cases = 'abcdefghjkmnpqrstuvwxy'
_upper_cases = _letter_cases.upper()
_numbers = ''.join(map(str, range(3, 10)))
init_chars = ''.join((_letter_cases, _upper_cases, _numbers))

def creat_validata_code(size=(120,30),chars=init_chars,img_type='jpg',
                        mode='RGB',bg_color=(255,255,255),fg_color=(0,0,255),
                            font_size=16,font_type='arial.ttf',
                            length=6,draw_lines=False,n_line=(1,2),
                            draw_points=False,point_chance=2):
    width,height = size;
    img = Image.new(mode, size, bg_color)
    
    draw = ImageDraw.Draw(img)
    
    def get_chars():
        return random.sample(chars,length)
    
    def creat_line():
        line_num = random.randint(*n_line)#sign that the param is a list
        
        for i in range(line_num):
            begin = (random.randint(0, size[0]), random.randint(0, size[1]))
            end = (random.randint(0, size[0]), random.randint(0, size[1]))
            draw.line([begin, end], fill=(0, 0, 0))
    
    def create_points():
        chance = min(100, max(0, int(point_chance)))
        for w in range(width):
            for h in range(height):
                tmp = random.randint(0, 100)
                if tmp > 100 - chance:
                    draw.point((w, h), fill=(0, 0, 0))
    
    def create_strs():
        c_chars = get_chars()
        strs = ' %s ' % ' '.join(c_chars)
        font = ImageFont.truetype(font_type, font_size)
        font_width, font_height = font.getsize(strs)
        draw.text(((width - font_width) / 3, (height - font_height) / 3),
                    strs, font=font, fill=fg_color)
        return ''.join(c_chars)
    
    if draw_lines:
        creat_line()
    if draw_points:
        create_points()
    strs = create_strs()

    params = [1 - float(random.randint(1, 2)) / 100,
              0,
              0,
              0,
              1 - float(random.randint(1, 10)) / 100,
              float(random.randint(1, 2)) / 500,
              0.001,
              float(random.randint(1, 2)) / 500
              ]
    img = img.transform(size, Image.PERSPECTIVE, params)
    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
    return img, strs



具体使用,可以这样,在django的views.py中:
程序代码 程序代码

def verify_code(request):    
    img, strs = verify_code_helper.creat_validata_code();
    request.session['verifycode'] = strs.lower()
    jpeg_image_buffer = BytesIO()
    img.save(jpeg_image_buffer, format="png")  
    response = HttpResponse(jpeg_image_buffer.getvalue())
    return response


剩下的应该都知道怎么做了,html页面与原来没什么差别,可以参考上面提到的两篇文章。
http://www.yihaomen.com/article/python/217.htm(python pil 验证码,汉字验证码)
http://www.yihaomen.com/article/python/573.htm(python/django生成动态验证码, 动态刷新, 直接修改 img src 属性)


除非申明,文章均为一号门原创,转载请注明本文地址,谢谢!
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: python3 django
相关日志:
评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.