码迷,mamicode.com
首页 > 其他好文 > 详细

Django---验证码

时间:2018-02-05 21:48:11      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:fill   gpo   end   random   for   获取   json   rom   and   

四种返回前端的方法

现在介绍第四种

import json
import random
from io import BytesIO
from  PIL import Image, ImageDraw, ImageFont

def get_rgb_func():
    """
    获取三原色
    :return: 三个元组
    """
    return (random.randint(1,255),random.randint(1,255),random.randint(1,255))


def get_imge(request):
    image = Image.new(mode="RGB", size=(130, 60), color=get_rgb_func())
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype("static/fonts/kumo.ttf",size=36)
    f = BytesIO()
    temp = []
    for i in range(5):
        random_char = random.choice([str(random.randint(0,9)),chr(random.randint(65,90)),chr(random.randint(97,122))])
        draw.text((i*27,10),random_char,get_rgb_func(),font=font)
        temp.append(random_char)
    width = 120
    height = 80

    for i in range(80):
        draw.point((random.randint(0,width),random.randint(0,height)),fill=get_rgb_func())

    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)
        draw.line((x1,y1,x2,y2),fill=get_rgb_func())
    for i in range(40):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=get_rgb_func())
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_rgb_func())
    image.save(f, "png")
    data = f.getvalue()
    request.session["random_char"] = ‘‘.join(temp)
    return HttpResponse(data)

 

Django---验证码

标签:fill   gpo   end   random   for   获取   json   rom   and   

原文地址:https://www.cnblogs.com/huyangblog/p/8419295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!