Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Introduction – We all know that HTTP is a stateless protocol. So how do clients and servers keep track of the status of logins — that is, how do they maintain logins?

(For example, if you log in to your iQiyi account in your browser, even if your website is closed, as long as it is not long, you will find that you have logged in again without entering your account!)

What is a cookie:

A file stored in key-value pairs on the browser of the client, like a dictionary {‘k’:’v’}, has nothing to do with the server. When the browser accesses the server, the server will generate a random string stored in the cookie and return it to the client. In this way, when the client visitor visits the server next time, it will visit the server with the saved cookie. After the server receives the request, it checks that the cookie already exists in this random string, indicating that the client has been authenticated and can log in directly.

More detailed explanation – “a 10,000-word blog takes you into the pit crawler this road of no return (you still hesitate what & hurry to get on the car)” [❤️ stay up late collation & suggested collection ❤️]

This uses the cookie in the browser:

For example – after logging in CSDN, click on the picture you can see CSDN stored in your local browser cookie information!

Setting cookies and getting deleted cookies on the server using Django:

import datetime
def set(request) :
    response = HttpResponse('setting cookies')
    #response.set_cookie('name', 'xiaoming '
    #response.set_cookie('name', 'xiaoming', max_age=100) # 100s
    response.set_cookie('name'.'xiaoming', expires=datetime.datetime(2020.10.1))  # specify expiration time
    return response

def get(request) :
    cookie = request.COOKIES
    print(cookie.get('name'))
    return HttpResponse('get a cookie)

def delete(request) :
    rs = HttpResponse('delete cookies')
    rs.delete_cookie('name')
    return rs
Copy the code

Note:

  1. Setting the cookie value and deleting the cookie value are both operations of the Response object, and obtaining the cookie is obtained from the requeset corresponding.
  2. While cookies can save state, be careful not to store sensitive information.

🔆 In The End!

Start now, stick to it, a little progress a day, in the near future, you will thank you for your efforts!

This blogger will continue to update the basic column of crawler and crawler combat column, carefully read this article friends, you can like the collection and comment on your feelings after reading. And can follow this blogger, read more crawler in the days ahead!

If there are mistakes or inappropriate words can be pointed out in the comment area, thank you! If reprint this article please contact me for my consent, and mark the source and the name of the blogger, thank you!