Django Cookies and Sessions
A cookie is a text file stored on the client's computer that retains various tracking information.
Identifying returning users involves three steps:
The server script sends a set of cookies to the browser. For example: name, age, or identification number.
The browser stores this information locally on the computer for future use.
The next time the browser sends any request to the web server, it sends these cookie information to the server, which uses this information to identify the user.
HTTP is a "stateless" protocol, meaning each time the client retrieves a webpage, the client opens a separate connection to the web server, and the server does not automatically retain any record of previous client requests.
However, there are 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, which can be used to identify subsequent requests from the client.
In web development, sessions are used for session tracking, with sessions relying on cookie technology.
Cookie Syntax in Django
Setting a cookie:
rep.set_cookie(key, value, ...)
rep.set_signed_cookie(key, value, salt='encryption salt', ...)
Getting a cookie:
request.COOKIES.get(key)
Deleting a cookie:
rep = HttpResponse || render || redirect
rep.delete_cookie(key)
Creating Applications 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()
print(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):
print(request.COOKIES.get('is_login'))
status = request.COOKIES.get('is_login') # Receives the browser's subsequent request, checks if the browser carries the cookie from the successful login response
if not status:
return redirect('/login/')
return render(request, "index.html")
def logout(request):
rep = redirect('/login/')
rep.delete_cookie("is_login")
return rep # Executes when logging out, deletes the cookie, no longer saves user status, and redirects to the login page
def order(request):
print(request.COOKIES.get('is_login'))
status = request.COOKIES.get('is_login')
if not status:
return redirect('/login/')
return render(request, "order.html")
The following creates three template files: login.html, index.html, and 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>
index.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>
order.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>
</html>
The session (a key-value pair stored on the server-side) allows the server to create a unique session object for each user's browser. Since the session is exclusive to the user's browser, data can be stored in the session and retrieved by other web resources on the server when the user accesses them.
Working Principle
- a. The browser's first request retrieves the login page.
- b. The browser's second request with username and password, if correct, the server responds with the index page and a cookie with a key 'sessionid' and a random string value, i.e., set_cookie("sessionid", random string).
- c. The server records data in the django.session table.
- session_key: Stores the random string, the value corresponding to the 'sessionid' key in the cookie.
- session_data: Stores user information, multiple request.session["key"]=value, and is encrypted.
- expire_date: Stores the expiration date of the record (default 14 days).
- d. The browser's third request for other resources carries the cookie: {sessionid: random string}, the server retrieves the user's data from the django.session table using the random string for its use (maintaining state).
Note: The django.session table stores browser information, not individual user information. Therefore, multiple user requests from the same browser only save one record (latter overrides former), while multiple browser requests save multiple records.
Cookies弥补了HTTP无状态的不足,让服务器知道来的人是"谁",但是cookie以文本的形式保存在浏览器端,安全性较差,且最大只支持4096字节,所以只通过cookie识别不同的用户,然后,在对应的session里保存私密的信息以及超过4096字节的文本。
Session setting:
request.session["key"] = value
Execution steps:
- a. Generate a random string.
- b. Save the random string and the key-value pair to the session_key and session_data in the django_session table.
set_cookie("sessionid", random_string)This is a Chinese to English translation, please provide the English translation for this text. Do not provide any explanations or text apart from the translation. Setting a `cookie`:
request.session.get('key')Response to the browser. Session retrieval:
request.session.flush()Execution steps: - a. Retrieve the value of the sessionid key from the cookie, which is a random string. - b. Filter the record from the django_session table based on the random string. - c. Extract the data from the session_data field. Session deletion, delete the entire record (including session_key, session_data, expire_date fields):
del request.session["key"]Deleting a specific key-value pair from session_data:
from session import views as session_viewsExecution steps: - a. Retrieve the value of the sessionid key from the cookie, which is a random string. - b. Filter the record from the django_session table based on the random string. - c. Delete the filtered record. ### Example Creating routes: ## urls.py
urlpatterns = [ path('session_login/', session_views.login), path('s_index/', session_views.s_index), path('s_logout/', session_views.s_logout), ]
Creating view functions:
## 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()
print(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 specific key-value pair from session_data request.session.flush() # Delete the entire record including (session_key, session_data, expire_date) fields return redirect('/session_login/')
Template file:
## s_index.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> </html> ```
The result is shown in the following image: