Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3648531
  • 博文数量: 365
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2522
  • 用 户 组: 普通用户
  • 注册时间: 2019-10-28 13:40
文章分类

全部博文(365)

文章存档

2023年(8)

2022年(130)

2021年(155)

2020年(50)

2019年(22)

我的朋友

分类: Python/Ruby

2021-08-19 17:24:03

工具类代码

# coding=utf-8

import random

from io import BytesIO

from PIL import Image,ImageFont,ImageDraw

def GetCode():

    source = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890'

    code = ""

    for i in range(4):

        code += random.choice(source)

    return code

def Set_Color():

    return random.randrange(255)

def Send_code_img(request):

    color_bg = (Set_Color(), Set_Color(), Set_Color())

    image = Image.new("RGB", size=(150, 50), color=color_bg)

    imagedraw = ImageDraw.Draw(image, "RGB")

    font = ImageFont.truetype("/static/Font/ALGER.TTF", 55)

    YanZhen_code = GetCode()

    imagedraw.text(xy=(0, 0), text=YanZhen_code, font=font, fill=(255, 255, 255))

    request.session["verify_code"]=YanZhen_code

    for i in range(800):

        # 绘制干扰点

        imagedraw.point(xy=(random.randrange(150), random.randrange(50)), fill=(Set_Color(), Set_Color(), Set_Color()))

    # image.show()

    fp = BytesIO()

    image.save(fp,"png")

    return fp.getvalue()

if __name__=="__main__":

    pass

views的代码

from django.http import HttpResponse, HttpResponseRedirect

from django.shortcuts import render, redirect

from django.urls import reverse

from django.views.decorators.csrf import csrf_exempt

from APP.TOOLS.YanZhen import Send_code_img

def Mine(request):

    return HttpResponse("欢迎登录")

@csrf_exempt

def Login(request):

    if request.method == "GET":

        return render(request, "YanZhen.html")

    elif request.method == "POST":

        post_code = request.POST.get("Get_code")

        verify_code = request.session.get("verify_code")

        if post_code.lower() != verify_code.lower():

            return redirect(reverse("APP:Login"))

        return redirect(reverse("APP:Mine"))

def Get_code_img(request):

    code_img = Send_code_img(request)

    return HttpResponse(code_img, content_type='image/png')

HTML代码

    

    </span><span style="font-family:宋体;">验证码验证</span><span style="font-family:Calibri;">

    {% load static %}

    请输入验证码:请输入验证码">

    

    

    

    

阅读(5807) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~