[Django] The role of cookie, session, setting read and other operations

1.cookie

Because the HTTP protocol is stateless and the server cannot distinguish between different users, the cookie was invented in 1993. In fact, a cookie is actually a small piece of text information stored in the user’s browser

Cookies probably have the following characteristics

  • It stores information in the form of key-value pairs
  • Based on domain name security, cookies of different domain names cannot access each other
  • It will automatically follow the current request to the server where the corresponding domain name is located
1.1 Set cookies

In Django, we can use the set_cookie() method of the HttpResponse object to set cookies

# 创建响应对象
response = HttpResponse()
# 使用响应对象设置Cookie
response.set_cookie(key, value, max_age=36000)

The above max_age parameter sets the validity period, the unit is seconds, the default is None, which is temporarily effective

class BooksView(View):
    def get(self, request):
        # 返回一个字典
        contents = {
    
    
            "title": "红楼梦",
            "read": "100",
            "others": [
                "人民教育出版社", "发行信息", "版权所有"
            ]
        }

        # 获取一个response对象
        response = render(request, 'books.html', contents)

        # 设置一个临时cookie
        response.set_cookie('name', 'admin', max_age=None)
        return response

1.2 Remove cookie

When the browser initiates a request with a cookie, we can read the cookie on the server

class BooksView(View):
    def get(self, request):
		...
        # 取出浏览器发送过来的cookie
        name = request.COOKIES.get("name")
        print('获取到的cookie:', name)
		...
        return response

2.session

Generally speaking, we do not store important information in cookies, because cookies can be seen by the front end. If it is sensitive information, it is easy to be leaked, but we can store these important information on the server side, which is the session

Session mechanism
When the client initiates a request, the server will save the user information with a random key (session_key), the corresponding value (session_data) is the user information, and then send this key to the client, that is, The cookie of the client, the next time the client accesses the server with a cookie, the server will retrieve the corresponding user information based on the cookie

Features of session

  • Do not expose sensitive information
  • Can store more content than cookies
  • Dependency and cookie
  • Session sharing, session can be managed uniformly through the cluster
2.1 Set session

It can be set through the session attribute of the HttpRequest() object

request.session['key'] = value

We continue to set the session in the previous view function

class BooksView(View):
    def get(self, request):
		...
        # 通过HttpRequest对象设置session
        request.session['name'] = 'admin'

        return response

When we refresh the page, we can see that in addition to the cookie set before the response header is returned, a string of sessionid appears

Insert picture description here

2.2 Read session

The reading of the session is the same as the reading of the cookie , except that the operating objects used by the cookie are all HttpResponse(), and the session is HttpRequest()

class BooksView(View):
    def get(self, request):
     	...
        # 通过HttpRequest对象设置session
        request.session['name'] = 'admin'

        # 读取Session
        name = request.session.get('name')
        print('session: ', name)

        return response

In addition, Django will save the session in the database, but the corresponding value is encrypted

Insert picture description here

2.3 Other operations of session

The main operation of the session is to set and read, and there are other operations to understand

清除所有Session,在存储中删除值部分
request.session.clear()

清除session数据,在存储中删除session的整条数据
request.session.flush()

删除session中的指定键及值,在存储中只删除某个键及对应的值
del request.session['key']

设置session的有效期
request.session.set_expiry(value)

Guess you like

Origin blog.csdn.net/qq_39147299/article/details/108287108