Django---验证码

Posted hpython

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django---验证码相关的知识,希望对你有一定的参考价值。

四种返回前端的方法

现在介绍第四种

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---验证码的主要内容,如果未能解决你的问题,请参考以下文章

django基础知识之验证码:

django之图形验证码生成

Django框架之验证码生成示例

php生成各种验证码

JSP 设计教师与学生不同登陆界面(带验证码)

Django REST框架--认证和权限