current position:Home>Python generates and deploys verification codes with one click (Django)

Python generates and deploys verification codes with one click (Django)

2021-08-23 06:45:15 ChinaUnix blog

Tool class code

# 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 ="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))


    for i in range(800):

        # Plot interference point

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


    fp = BytesIO(),"png")

    return fp.getvalue()

if __name__=="__main__":


views Code for

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(" Welcome to login ")


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')



    </span><span style="font-family: Song style ;"> Verification code verification </span><span style="font-family:Calibri;">

    {% load static %}

     Please enter the verification code : Please enter the verification code ">





copyright notice
author[ChinaUnix blog],Please bring the original link to reprint, thank you.

Random recommended