Django uses pillow to simply set up verification code function (python)

Django uses pillow to simply set up verification code function (python)

1. Import the module and define a validation state

from PIL import Image, ImageDraw, ImageFont
from django.utils.six import BytesIO
def verify_code(request):
  #Introduce the random function module import random
  #Define variables for the background color, width, and height of the screen bgcolor = (random.randrange(20, 100), random.randrange(
    20, 100), 255)
  width = 100
  height = 25
  #Create screen object im = Image.new('RGB', (width, height), bgcolor)
  #Create a brush object draw = ImageDraw.Draw(im)
  #Call the point() function of the brush to draw noise for i in range(0, 100):
    xy = (random.randrange(0, width), random.randrange(0, height))
    fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
    draw.point(xy, fill=fill)
  #Define the alternative value of the verification code str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
  #Randomly select 4 values ​​as verification codes rand_str = ''
  for i in range(0, 4):
    rand_str += str1[random.randrange(0, len(str1))]
  #Construct font object, Ubuntu's font path is "/usr/share/fonts/truetype/freefont"
  font = ImageFont.truetype('FreeMono.ttf', 23)
  #Construct font color fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
  #Draw 4 words draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
  draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
  draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
  draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
  #Release the brush del draw
  #Save to session for further verification request.session['verifycode'] = rand_str
  #Memory file operation buf = BytesIO()
  #Save the image in memory, the file type is png
  im.save(buf, 'png')
  #Return the image data in memory to the client, the MIME type is image png
  return HttpResponse(buf.getvalue(), 'image/png') 

3. Put it directly into img on the web page

<img src="/verify_code/" alt="驗證碼">

4. Use ajax to obtain verification password and account

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>login</title>
</head>
<body>
<h1 class="show"></h1>
<input type="text" id = username value="{{username}}"> <br>
<input type="text" id = password> <br>
<input type="text" id = yum> <a>Please enter the verification code</a> <br>
<img src="/verify_code/" alt="Verification code">
<input type="button" id="Ajax" value="ajax login"> <br>
<input type="checkbox" id = "ow" name="ow"> Remember password<br>
<a href="/get_cookies">Click to get cookies</a>
</body>
<script src="/static/index/js/jquery-3.3.1.min.js"></script>
</html>
<script>
  $(function () {
    $('#Ajax').click(function () {
        username = $('#username').val();
        password = $('#password').val();
        ow = $("#ow").val();
        yum = $('#yum').val();
        $.ajax({
          'url': '/loginajax',
          'type': 'post',
          'data': {'username': username, 'password': password,
                "yum":yum,},
          'success':function(data){
          //Login successfully returns 1
          //Return 0 if login failed
            //Verification failed, return 3
          if (data.res == 1) {
            $('.show').show().html('Login successful')
          } else if (data.res == 0) {
            $('.show').show().html('Login failed')
          } else if (data.res == 3){
            $('.show').show().html('Verification code input failed')
          }
        }
        });
      });
  });
</script>

In the above ajax, the account password and verification code are sent to the server

In the validation function

  yzm = request.POST.get('yum') # Get the verification code vaue = request.session['verifycode'] # Save the verification code in the session when generating the image if yzm !=vaue: #If they are not equal, it will return 3 HTML ajax will display the verification error return JsonResponse({'res':3})

Results:

Summarize

The above is what I introduced to you. Django uses pillow to simply set up the verification code function (python). I hope it will be helpful to you. If you have any questions, please leave me a message and I will reply to you in time. I would also like to thank everyone for their support of the 123WORDPRESS.COM website!
If you find this article helpful, please feel free to reprint it and please indicate the source. Thank you!

You may also be interested in:
  • Python uses Pillow (PIL) library to implement the whole process of verification code picture
  • Python3 pillow module implements simple verification code
  • Python3 uses pillow library to generate random verification code
  • Python3 pillow generates a simple verification code image example
  • Python example code for identifying dynamic verification codes through pillow

<<:  How React Hooks Work

>>:  Python 3.7 installation tutorial for MacBook

Recommend

Implementation of LNMP for separate deployment of Docker containers

1. Environmental Preparation The IP address of ea...

Docker image optimization (from 1.16GB to 22.4MB)

Table of contents The first step of optimization:...

Detailed explanation of Vue Notepad example

This article example shares the specific code of ...

A brief discussion on Mysql specified order sorting query

Recently, I have been working on a large-screen d...

Specific use of useRef in React

I believe that people who have experience with Re...

Building FastDFS file system in Docker (multi-image tutorial)

Table of contents About FastDFS 1. Search for ima...

Specific usage of Vue's new toy VueUse

Table of contents Preface What is VueUse Easy to ...

MySQL query sorting and paging related

Overview It is usually not what we want to presen...

Detailed example of using if statement in mysql stored procedure

This article uses an example to illustrate the us...

Detailed explanation of MYSQL stored procedure comments

Table of contents 1. Instructions for use 2. Prep...

A solution to a bug in IE6 with jquery-multiselect

When using jquery-multiselect (a control that tra...

Native JS to achieve cool paging effect

This article uses an example to share with you a ...

Configure Java development environment in Ubuntu 20.04 LTS

Download the Java Development Kit jdk The downloa...