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

A brief introduction to the general process of web front-end web development

I see many novice students doing front-end develop...

MySQL 5.5.27 winx64 installation and configuration method graphic tutorial

1. Installation Package MYSQL service download ad...

Sample code for implementing a background gradient button using div+css3

As the demand for front-end pages continues to in...

Detailed explanation of semiotics in Html/CSS

Based on theories such as Saussure's philosop...

MySQL free installation version configuration tutorial

This article shares the MySQL free installation c...

JavaScript implements Tab bar switching effects

Here is a case that front-end developers must kno...

...

VUE + OPENLAYERS achieves real-time positioning function

Table of contents Preface 1. Define label style 2...

Some understanding of absolute and relative positioning of page elements

From today on, I will regularly organize some smal...

MySQL optimization connection optimization

In the article MySQL Optimization: Cache Optimiza...

JavaScript to implement dynamic digital clock

This article shares the specific code for impleme...

Vue Page Stack Manager Details

Table of contents 2. Tried methods 2.1 keep-alive...

Write a formal blog using XHTML CSS

The full name of Blog should be Web log, which mea...