Python verification code based on Django (example), djangopython

Source: Internet
Author: User

Python verification code based on Django (example), djangopython

Verification Code

On the user registration and logon page, you can add the verification code function to prevent brute-force requests. If the verification code is incorrect, you do not need to proceed with the verification code. This reduces the pressure on some servers.

Verification Code is also an effective method to prevent crsf

The verification code is as follows:

Verification Code view

Create viewsUtil. py and define the function verifycode

This Code uses the Image, ImageDraw, and ImageFont modules in PIL. You must first install the Pillow (3.4.1) package,

Detailed document reference http://pillow.readthedocs.io/en/3.4.x/

Image indicates the canvas object

ImageDraw indicates the paint brush object.

ImageFont indicates the font object. The ubuntu font path is "/usr/share/fonts/truetype/freefont"

The Code is as follows:

From django. http import HttpResponsedef verifycode (request): # introduce the drawing module from PIL import Image, ImageDraw, ImageFont # introduce the random function module import random # define the variable, bgcolor = (random. randrange (20,100), random. randrange (20,100), 255) width = 100 height = 25 # Create Image Object im = Image. new ('rgb ', (width, height), bgcolor) # create the paint brush object draw = ImageDraw. draw (im) # Call the point () function of the paint 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 = 'abc123efghijk456lmnopqrs789tuvwxyz0' # randomly select four values as the verification code rand_str = ''for I in range (0, 4): rand_str + = str1 [random. randrange (0, len (str1)] # construct the font object font = ImageFont. truetype ('freemono. ttf', 23) # construct 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 paint brush del draw # Save it to the session for further verification request. session ['verifycode'] = rand_str # memory file operation import io buf = io. stringIO () # Save the image in the memory. The file type is png im. save (buf, 'png ') # return the image data in the memory to the client. The MIME type is png return HttpResponse (buf. getvalue (), 'image/png ')

Configure url

Define the url of the request verification code view in urls. py

from . import viewsUtilurlpatterns = [ url(r'^verifycode/$', viewsUtil.verifycode),]

Show Verification Code

• Use the img label in the template. src points to the Verification Code view.

 

• Start the server and check that the server is successfully started.

• Extension: When you click "cannot see clearly, change one", you can change a new verification code.

<Script type = "text/javascript" src = "/static/jquery-1.12.4.min.js"> </script> <script type = "text/javascript"> $ (function () {comment ('{verifycodechange'}.css ('cursor ', 'pointer '). click (function () {$ ('# verifycode '). attr ('src', $ ('# verifycode '). attr ('src') + 1)}) ;}); </script>  <span id = 'verifycodechang'> can't see clearly, change one </span>

• To implement the submission function, you need to add the form and input labels.

<Form method = 'post' action = '/verifycodeValid/'> <input type = "text" name = "vc">  <span id = 'verifycodechang'> cannot see clearly, change one </span> <br> <input type = "submit" value = "submit"> </form>

Verify

• Received request information, compared with the content in the session

from django.http import HttpResponsedef verifycodeValid(request):  vc = request.POST['vc']  if vc.upper() == request.session['verifycode']:    return HttpResponse('ok')  else:    return HttpResponse('no')

• Configure the url for verification

urlpatterns = [  url(r'^verifycodeValid/$', views.verifycodeValid),]

The above python verification code based on Django (for example) is all the content shared by the editor. I hope you can give us a reference and support the help house.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.