cookies and session s in django

Posted by xtian on Sun, 27 Feb 2022 00:56:09 +0100

Cookies and session s

Keep the session state and record login, browsing and other information
From opening the browser to visit a website to closing the browser to end the visit, it is called a session
http protocol is stateless, which makes it difficult to maintain the session

cookie and session are two storage technologies born to maintain the session state

cookies

cookies - Definition

cookies are storage space stored on the client browser

cookies - features

1. cookies In the browser, it is stored in the form of key value pairs, which can be regarded as a dictionary. Keys and values are stored in ascii String storage
2. Stored data has a lifecycle
Expires / Max-Age:"Sat, 18 Feb 2023 03:42:31 GMT"
3. cookies The data in is stored and isolated by domain, and cannot be accessed between different domains
4. cookies The internal data of will be carried to the server every time you visit this website. If cookies Too large will reduce the response speed

Use of cookies - Settings

You can use httpresponse set_ Cookies setting cookie s

HttpResponse.set_cookie(key,value='',max_age=None,expires=None)
key:  cookie Name of
values:  coolie Value of
max_age: cookie Survival time of, in seconds
expires:  Specific expiration time
 When not specified max_age and expires When, close the browser, and the data is invalid

route

   path('set_cookies/',views.set_cookies)

View layer

def set_cookies(request):
    from django.http import HttpResponse, HttpResponseRedirect
    resp = HttpResponse('set coolies is ok')
    resp.set_cookie("hello","world",200)
    return resp

Storage example:
Add cookie

def set_cookies(request):
    resp = HttpResponse("Added my_var1,The value is 123")
    # Add key for browser as my_ A cookie with a value of 123 and an expiration time of 1 hour
    resp.set_cookie("my_var1",123,3600)
    return resp

Modify cookie

# Add key for browser as my_ The value of VAR1 is modified to 456, which is a cookie with an expiration time of 2 hours
resp = HttpResponse("modify my_var1,The value is 456")
resp.set_cookie("my_var1",456,3600*2)
return resp

delete cookies

HttpResponse.delete_cookie(key)
Delete the cookie of the specified key. If the key does not exist, ignore it

Get cookie

Pass request Obtain client cookie data from the dictionary bound to cookies
value=request.COOKIES.get('cookie name ',' default ')

def get_cookies(request):
    value=request.COOKIES.get("my_var1")
    return HttpResponse('cookies is %s'%value)

session

session features

session is to open up a space on the server (django is in the database) to retain important data when the browser interacts with the server

session settings

Implementation method:

  1. To use session, you need to start the cookie on the browser client and store the sessionid in the cookie
  2. Each client can have an independent session on the server
  3. Different requesters will not share data, but correspond to requesters one by one

settings.py configure session

  1. To installed_ Add to the apps list (enabled by default)
# Enable session application
'django.contrib.sessions',
  1. Add to the midview list (enabled by default)
'django.contrib.sessions.middleware.SessionMiddleware',

Use of session

session for an object of SessionStore type similar to a dictionary, it is operated by operating the dictionary.

session can store string, integer, dictionary list, etc

  1. Save the value of session to the server
    request.session['KEY']=VALUE
  2. Get the value of session
    value = request.session['KEY']
    value = request.session ['KEY', the default] # recommends this type. Even if there is no one, there will be no error
  3. Delete session
    del request.session['KEY']

settings. Relevant configuration items in PY

  1. session_cookie_age
    Function: specify the saving time of session in cookies (2 weeks by default)
    SESSION_COOKIE_AGE=60602472

  2. SESSION_EXPIRE_AT_BROWSER_CLOSE=TRUE
    Set that the session will fail as long as the browser is closed (the default is False)

Note: the session data in Django is stored in the database, so you need to ensure that you have migrate d before using session

mysql> desc django_session;
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| session_key  | varchar(40) | NO   | PRI | NULL    |       |
| session_data | longtext    | NO   |     | NULL    |       |
| expire_date  | datetime(6) | NO   | MUL | NULL    |       |
+--------------+-------------+------+-----+---------+-------+
3 rows in set (0.04 sec)
mysql> select * from django_session;
+----------------------------------+----------------------------------------------------------------------------------+----------------------------+
| session_key                      | session_data                                                                     | expire_date                |
+----------------------------------+----------------------------------------------------------------------------------+----------------------------+
| 5rhg0l78xbz136g3axxhobgh1rtp604i | ZmNkZTMzZDExY2M0ZmQ0Mjg1OTZiOTg4ZWI2YzAxNjY4MjkyYjcyZjp7InVuYW1lIjoic2h1Z2UifQ== | 2022-03-04 06:24:20.452528 |
+----------------------------------+----------------------------------------------------------------------------------+----------------------------+
1 row in set (0.01 sec)

Django session

  1. Django_session means that a single table is involved, and the data volume of the table continues to increase [even if the expiration time is reached, the data in the table will not be cleared; or if the sessionid in the browser is manually deleted, the data in the table will not be cleared]
  2. You can execute Python manage every night Py clearsessions [this command can delete expired session data]

Comparison of cookies and session s

Topics: Python Django server