Django Cookie and Session
A cookie is a text file stored on the client's computer that retains various tracking information.
Identifying a returning user involves three steps:
- The server script sends a set of Cookies to the browser, for example: name, age, or identification number, etc.
- The browser stores this information on the local computer for future use.
- The next time the browser sends any request to the Web server, it sends this Cookie information to the server, which uses it to identify the user.
HTTP is a "stateless" protocol, which means that each time the client retrieves a web page, the client opens a separate connection to the Web server, and the server automatically does not retain any record of previous client requests.
However, there are still the following three ways to maintain a session between the Web client and the Web server:
Cookies
A Web server can assign a unique session ID as a cookie for each Web client, and subsequent requests from the client can be identified using the received cookie.
In Web development, sessions are used to track sessions, and sessions rely on Cookie technology underneath.

Cookie syntax in Django
Set a cookie:
rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt='加密盐',...)
Get a cookie:
request.COOKIES.get(key)
Delete a cookie:
rep =HttpResponse || render || redirect
rep.delete_cookie(key)


Create the app and models
models.py
class
UserInfo
(
models.
Model
)
:
username
=
models.
CharField
(
max_length
=
32
)
password
=
models.
CharField
(
max_length
=
64
)

urls.py
from
django.
contrib
import
admin
from
django.
urls
import
path
from
cookie
import
views
urlpatterns
=
[
path
(
'admin/'
,
admin.
site
.
urls
)
,
path
(
'login/'
,
views.
login
)
,
path
(
'index/'
,
views.
index
)
,
path
(
'logout/'
,
views.
logout
)
,
path
(
'order/'
,
views.
order
)

views.py
def
login
(
request
)
:
if
request.
method
==
"GET"
:
return
render
(
request
,
"login.html"
)
username
=
request.
POST
.
get
(
"username"
)
password
=
request.
POST
.
get
(
"pwd"
)
user_obj
=
models.
UserInfo
.
objects
.
filter
(
username
=
username
,
password
=
password
)
.
first
(
)
(
user_obj.
username
)
if
not
user_obj:
return
redirect
(
"/login/"
)
else
:
rep
=
redirect
(
"/index/"
)
rep.
set_cookie
(
"is_login"
,
True
)
return
rep
def
index
(
request
)
:
(
request.
COOKIES
.
get
(
'is_login'
)
)
status
=
request.
COOKIES
.
get
(
'is_login'
)
Upon receiving another request from the browser, determine whether the cookie carried by the browser is the cookie responded when login succeeded
if
not
status:
return
redirect
(
'/login/'
)
return
render
(
request
,
"index.html"
)
def
logout
(
request
)
:
rep
=
redirect
(
'/login/'
)
rep.
delete_cookie
(
"is_login"
)
return
rep
Executed after clicking logout, delete the cookie, no longer save user state, and jump to the login page
def
order
(
request
)
:
(
request.
COOKIES
.
get
(
'is_login'
)
)
status
=
request.
COOKIES
.
get
(
'is_login'
)
if
not
status:
return
redirect
(
'/login/'
)
return
render
(
request
,
"order.html"
)
Create the following three template files: login.html, index.html, order.html.
login.html
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<title Title title head>
<body>
<h3>User login
h3
<form action="" method="post">{% csrf_token %}
<
p
Username:
<input type="text" name="username" p>
<p>Password:
<
input
type
=
"
password
"
name
=
"
pwd
"
p
<
input
type
=
"
submit
"
form
body
html
<!
DOCTYPE
html
<html lang="en">
<head>
<meta charset="UTF-8">
<title Title title head>
<body>
<h2>index page...
h2
<
a
href
=
"
/logout/
"
Logout
a
body
html
<!
DOCTYPE
html
<html lang="en">
<head>
<meta charset="UTF-8">
<title Title title head>
<body>
<h2>order page...
h2
<
a
href
=
"
/logout/
"
Logout
a
body
htmlThe running result is shown in the following figure:

Session (key-value pairs stored on the server side)
While running, the server can create a session object exclusive to each user's browser. Since a session is exclusive to a user's browser, when users access the server's web resources, they can put their own data in their own session; when users visit other web resources on the server, those resources retrieve data from the user's own session to serve them.

How It Works
-
a. The browser requests the login page for the first time.
-
b. The browser enters the account and password for the second request; if correct, the server responds with an index page and a cookie with key sessionid and a random string value, i.e., set_cookie ("sessionid", random string).
-
c. The server internally records a piece of data in the django.session table.
The django.session table has three fields.
- session_key: stores the random string, i.e., the value corresponding to the sessionid key of the cookie responded to the browser.
- session_data: stores the user's information, i.e., multiple request.session["key"]=value, and is ciphertext.
- expire_date: stores the expiration time of this record (default 14 days)
-
d. When the browser requests other resources for the third time, carrying cookie :{sessionid: random string}, the server retrieves the user's data from the django.session table based on this random string for use (i.e., saving state).
Note: The django.session table stores information about the browser, not about each user. Therefore, multiple users' requests from the same browser only save one record (later ones overwrite earlier ones); only requests from multiple browsers save multiple records.
Cookies compensate for the statelessness of http, letting the server know "who" the visitor is, but cookies are stored as text on the browser side with poor security and a maximum of only 4096 bytes, so cookies are used only to identify different users, and then private information and text over 4096 bytes are saved in the corresponding session.
Session settings:
request.session["key"] = value
Execution steps:
- a. Generate a random string
- b. Save the random string and the set key-value pairs to the session_key and session_data of the django_session table
- c. Set the cookie: set_cookie("sessionid", random string) responded to the browser
Session retrieval:
request.session.get('key')
Execution steps:
- a. Get the value of the sessionid key from the cookie, i.e., the random string.
- b. Filter out the record from the django_session table based on the random string.
- c. Extract the data in the session_data field.
Session deletion: delete the entire record (including the three fields session_key, session_data, expire_date):
request.session.flush()
Delete one of the key-value pairs in session_data:
del request.session["key"]
Execution steps:
- a. Get the value of the sessionid key from the cookie, i.e., the random string
- b. Filter out the record from the django_session table based on the random string
- c. Delete the filtered-out record
Example
Create the route:
urls.py
from
session
import
views
as
session_views
urlpatterns
=
[
path
(
'session_login/'
,
session_views.
login
)
,
path
(
's_index/'
,
session_views.
s_index
)
,
path
(
's_logout/'
,
session_views.
s_logout
)
,
]

Create the view function:
views.py
def
login
(
request
)
:
if
request.
method
==
"GET"
:
return
render
(
request
,
"login.html"
)
username
=
request.
POST
.
get
(
"username"
)
password
=
request.
POST
.
get
(
"pwd"
)
user_obj
=
models.
UserInfo
.
objects
.
filter
(
username
=
username
,
password
=
password
)
.
first
(
)
(
user_obj.
username
)
if
not
user_obj:
return
redirect
(
"/session_login/"
)
else
:
request.
session
[
'is_login'
]
=
True
request.
session
[
'user1'
]
=
username
return
redirect
(
"/s_index/"
)
def
s_index
(
request
)
:
status
=
request.
session
.
get
(
'is_login'
)
if
not
status:
return
redirect
(
'/session_login/'
)
return
render
(
request
,
"s_index.html"
)
def
s_logout
(
request
)
:
del request.session["is_login"] # delete a key-value pair in session_data
request.
session
.
flush
(
)
Delete one record including the three fields (session_key session_data expire_date)
return
redirect
(
'/session_login/'
)
Template files:
s_index.html
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<title Title title head>
<body>
<h2>session_index page... {{ request.session.user1 }}
h2
<
a
href
=
"
/s_logout/
"
Logout
a
body
htmlThe running result is shown in the following figure:
