Blog Park Project-Login (verification code, AJAX submission data, session and cookie)

Source: Internet
Author: User

Front Page
{% load static%}<! DOCTYPE html>

You can see the user access to the login page, in the case of the verification code image will be accessed/get_valid_img/, through the URL to get the captcha image

The user's data is submitted to the backend via Ajax, and when the backend finishes validating, if it is validated, jumps to the first page and, if it fails, adds the error message

Generate Random Verification code
def get_valid_img (Request): # from Utils.random_code import Get_random_code # Local module import cannot be used * # data = Get_random_code () Import Random Def get_random_color (): Return (random.randint (0, 255), Random.randint (0, 255), Random.randint    (0, 255)) # way 1: # f = open ("Car.jpg", "RB") # data = F.read () # f.close () # mode 2: Save picture to Disk # import PIL # from PIL I Mport Image # from IO import Bytesio # Image = image.new (mode= "RGB", size= (+), Color=get_random_color ()) #    f = open ("Code.png", "WB") # Image.Save (F, "PNG") # F.close () # f = open ("Code.png", "RB") # data = F.read () # f.close () # Way 3: Put the picture into memory # import PIL # from PIL import image # from IO import Bytesio # Image = IMAGE.N EW (mode= "RGB", size= (+), Color=get_random_color ()) # f = Bytesio () # Image.Save (F, "PNG") # # data = F.G Etvalue () # mode 4:from PIL import Image # PIL module can be downloaded by downloading Pillow module using from IO Import bytesio from PIL import Imagedr Aw, IMAGEFONT # Brush image = Image.new (mode= "RGB", size= (), Color=get_random_color ()) draw = Imagedraw.draw (image) Fon t = Imagefont.truetype ("Static/fonts/kumo.ttf", size=32) temp = [] for I in range (5): Random_char = random.ch Oice ([Chr (Random.randint), Chr (Random.randint (122)), str (random.randint (0, 9))]) Draw.text (  (i *, +), Random_char, Get_random_color (), Font=font) # parameters are coordinates, added string, Color, font temp.append (Random_char) # In order to make the generated verification code more confusing, we can use the following method to add a random dot line to the captcha image, etc. # for I in range: # Draw.point ((Random.randint (0,width), Random.ra Ndint (0,height)), Fill=get_random_color ()) # # for I in range: # X1=random.randint (0,width) # X2=ra Ndom.randint (0,width) # y1=random.randint (0,height) # y2=random.randint (0,height) # draw.line (X1,y1, X2,y2), Fill=get_random_color ()) # for I in range (max): # Draw.point ([Random.randint (0, width), random.randint (0, Height)], Fill=get_randoM_color ()) # x = Random.randint (0, width) # y = random.randint (0, height) # Draw.arc ((x, y, x + 4, y + 4), 0, Fill=get_random_color ()) F = Bytesio () image.save (F, "png") data = F.getvalue () # Save random string Rand Om_code_str = "". Join (temp) request.session["random_code_str"] = random_code_str "1 generate random String 2 response Set_cookie {"SessionID": "E21e12gg2d3sds"} 3 Insert a record in the Django_session table Session_key session_data "' Return HTTPRESP Onse (data)

Since the verification code needs to generate a picture, here we import the PIL module (the module used to generate the picture)

Sir, as an Image object, the color of the picture should be random, we define a function that generates 3 random numbers to form a tuple

Import Random    def get_random_color ():        return (random.randint (0, 255), Random.randint (0, 255), Random.randint ( 0, 255))

A random string is also required in the CAPTCHA, and we import imagedraw (brushes) from the PiL module, Imagefont (font)

First, create a Font object, download the font file, and store it in the project

Then generate the Font object from the font file

Font = Imagefont.truetype ("Static/fonts/kumo.ttf", size=32)  # size is font size

Then add content to the resulting image image, which should be a random string, generated and added to the image image in the following ways

Draw = Imagedraw.draw (image)  # Brush font = Imagefont.truetype ("Static/fonts/kumo.ttf", size=32) temp = []for i in range (5 ):    Random_char = Random.choice (        [Chr (Random.randint), Chr (Random.randint (), 122), STR ( Random.randint (0, 9)])    Draw.text ((i *, ii), Random_char, Get_random_color (), Font=font)    temp.append ( Random_char)

Since the verification code picture is only sent to the user for verification purposes, there is no need to save to the local disk, we can import Bytesio from the IO module, generate space in memory to hold the picture

From io Import bytesiof = Bytesio () image.save (F, "png") data = F.getvalue ()

When data is returned to the page, the user can see the captcha picture.

However, in order to facilitate our acceptance of the user input verification code after verification, we need to save the content of this build verification code

# save Random string random_code_str = "". Join (temp)

Now we need to consider a problem, using the above method to save the code content, if a user first visited the login page, at this time Random_code_str was given a value, and this is another user also visited the login page, RANDOM_CODE_STR will be overwritten by the latter value

Then the previous user entered the correct verification code can not be verified successfully

In this case, we need to ensure that each user can save their own access to the page verification code value, you can consider using the session

# save Random string random_code_str = "". Join (temp) request.session["random_code_str"] = Random_code_str

Here we need to know what Request.session has done:

1 Generating random strings
2 response Set_cookie {"SessionID": "E21e12gg2d3sds"}
3 inserting a record in the Django_session table

If a user accesses a cookie, the action updates the contents of the Session_data in the Database django_session table without changing other content such as Session_key.

Click Update Verification Code

When we log in, often encounter the verification code can not see the situation, at this time we could click on the verification code image to refresh

This function can be implemented by the front-end JS

    The CAPTCHA refreshes    $ ("img"). Click (function () {        $ (this) [0].src + = "    }")

Find the IMG tag of the captcha picture, give him a click event, pass the DOM object method, add one after the image src? can be accessed again,

Back-end validation
def log_in (Request):    response = {"Is_login": False, "error_msg": ""}    if Request.method = = "POST":        username = Request. Post.get ("user")        pwd = Request. Post.get ("pwd")        Valid_code = Request. Post.get ("Valid_code")        code_str = Request.session.get ("random_code_str")        if valid_code.upper () = = Code_ Str.upper ():            user = Auth.authenticate (username=username, password=pwd)            if User:                response["is_login"] = True                auth.login (Request, user)  # 1 {"user_id": 1} 2 Request.user=user            else:                response["Error_msg" ] = "Username Password error"        else:            response["error_msg"] = "Captcha error"        return HttpResponse (json.dumps (response))    return render (Request, "login.html")

We first verify that the verification code is correct, and then use the Auth component to authenticate the user name and password, if the verification code is correct.

It is important to note that when the username password is verified successfully, we use the Auth.login () method to write the session, but since the previous access to the verification code picture has generated a session record in the database, the method will flush clear the record before adding a new record

So then we see that the value of the SessionID in the cookie has changed, which is to be distinguished from the Request.session method used to generate the verification code.

Blog Park Project-Login (verification code, AJAX submission data, session and cookie)

Related Article

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.