SoFunction
Updated on 2024-10-29

Django manipulation cookie implementation

preamble

Cookie: In websites, http requests are stateless. This means that even after the first connection to the server and a successful login, the second request the server still does not know which user is currently requesting.cookiewas created to solve this problem, where the server returns some data after the first login(cookie)to the browser, then the browser saves it locally, and when that user sends a second request, it automatically stores the last request's storedcookieThe data is automatically carried to the server, and the server can determine the current user by the data carried by the browser.cookieThe amount of data stored is limited, and different browsers have different storage sizes, but generally no more than 4KB. so use thecookieOnly small amounts of data can be stored.

Cookie features:

(1) Stored in key-value pairs
(2) When a website is accessed through a browser, all cookie information stored by the browser in relation to the website is sent to the server of the website.
(3) Cookies are based on domain name security
(4) cookies have an expiration time, if you do not specify, by default, the cookie will expire after closing the browser

Cookie non-cross-domainizability

1, many websites will use cookies, for example, Google will issue cookies to the client, Baidu will also issue cookies to the client, the browser to visit Google will not also carry on the Baidu issued cookies? Or can Google modify the cookies issued by Baidu?

2, the answer is no. Cookie has no cross domain name. According to the Cookie specification, the browser to visit Google will only carry Google's Cookie, and will not carry Baidu's Cookie. Google can only operate Google's Cookie, and can not operate Baidu's Cookie!

3, Cookie in the client is managed by the browser. Browsers can ensure that Google will only operate Google's cookies and will not operate Baidu's cookies, thus ensuring the privacy and security of users. Browser to determine whether a site can operate another site cookies based on the domain name, Google and Baidu's domain name is not the same, so Google can not operate Baidu's cookies.

4, it should be noted that, although the site and the site belongs to Google, but the domain name is not the same, the two can not operate each other's cookies!

Setting cookies

set upcookieis setting the value to the browser. So we need to pass theresponseobject to set it, set thecookieThis can be done byresponse.set_cookieto set, the relevant parameters of this method are as follows:

  • key: the key of this cookie.
  • value: the value of this cookie.
  • max_age: the maximum life cycle. The unit is seconds.
  • expires: the expiration time. Similar to max_age, except that this parameter needs to be passed a specific date, such as datetime or a date-conforming string. If both expires and max_age are set, then the value of expires will be used as the expiration time.
  • path: which path is valid for the domain. Default is all paths under the domain.
  • domain: the domain name for which this attribute is valid. By default, it is valid for all domains under the main domain, if it is valid only for a sub-domain, then you can set this attribute.
  • secure: if or not it is secure, if it is set to True, then it can only be used under https protocol.
  • httponly: default is False. if it is True, then it can not be operated by JavaScript on the client side.

Getting cookies

Gets the data sent by the browsercookieInformation. This can be done through theto either. This object is a dictionary type. For example, to get all cookies, the sample code is as follows:

cookies = 
for cookie_key,cookie_value in ():
   print(cookie_key,cookie_value)

Delete cookies

pass (a bill or inspection etc)delete_cookiecan be deletedcookie. In fact, the deletion ofcookieis to set the specifiedcookievalue is set to an empty string, and then use to set his expiration time to 0, which means it expires when the browser is closed.

real-life example

We'll start with theThe code for writing three routes, a set cookie route, a get cookie route, and a delete cookie route, is as follows:

# Project root routing
urlpatterns = [
    path('cookie_app/', include('cookie_app.urls')),
]

# cookie_app.
urlpatterns = [
    path('set_cookie/', views.set_cookie),
    path('get_cookie/', views.get_cookie),
    path('delete_cookie/', views.delete_cookie),
]

Then we're in theThe code to write the corresponding view in the view is as follows:

def set_cookie(request):
    """Setting cookies"""
    response = HttpResponse('success')
    response.set_cookie('username', 'jkc', max_age=180)  # Set cookies with an expiration time of 180 seconds
    return response


def get_cookie(request):
    """Getting cookies"""
    cookies = 
    return HttpResponse(())


def delete_cookie(request):
    """Delete cookies"""
    response = HttpResponse('Deleted cookie successfully')
    response.delete_cookie('username')
    return response

Next we visit the url address127.0.0.1/cookie_app/set_cookie/Open.F12, we can see the network request in theresponse headerthere areset-cookiefield


We can also open the website address on theThe following chart shows the results.


Then the following pop-up window will appear, click on thecookie


We'll see the cookie we just set.usernameand the expiration time is the previously set 3 minutes.



Next we visithttp://127.0.0.1:8000/cookie_app/get_cookie/Getting a cookie, the browser page will return('username', 'jkc'), we can also open F12 to view the information in the request header, we will find that the request header carries thecookieinformation, as shown below


Finally we visithttp://127.0.0.1:8000/cookie_app/delete_cookie/Delete cookie, browser page returnsDelete Cookie SuccessfullyThen we look at the site'scookieInformation viewing will revealusernamevalue is null, as follows


Why is it set to empty? We can check thedelete_cookieThe source code for the method, as follows

def delete_cookie(self, key, path='/', domain=None):
    # Most browsers ignore the Set-Cookie header if the cookie name starts
    # with __Host- or __Secure- and the cookie doesn't use the secure flag.
    secure = (('__Secure-', '__Host-'))
    self.set_cookie(
        key, max_age=0, path=path, domain=domain, secure=secure,
        expires='Thu, 01 Jan 1970 00:00:00 GMT',
    )

As you can see, it actually has a call to theset_cookiemethod and then didn't give thevalueAssigning a value defaults to the''empty string, then set themax_ageis 0, which means that the expiration time is now, immediately.

to this article on the realization of Django cookie operation is introduced to this article , more related Django cookie operation content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future !