Django-cookie和session

文章目录


前言

Cookie 是由服务器发送到用户浏览器的小文件,用于存储用户的相关信息。每次用户访问网站时,浏览器会将这些 cookie 发送回服务器

bash 复制代码
特点:
1. 数据存储在客户端,大小通常限制在 4KB
2. 过期时间可以设置,默认是会话级别
3. 用户可以手动删除 cookie

Session

Session 是一种在服务器端存储用户数据的机制,用户的数据以会话的方式保存。Django 会为每个用户生成一个唯一的 session ID,并将其存储在客户端的 cookie 中

bash 复制代码
特点:
1. 数据存储在服务器端,可以存储更大和复杂的数据结构
2. 更安全,因为用户不能直接访问 session 数据
3. 自动管理会话的过期时间

假设你想在用户的浏览器中存储一个用户的用户名,以便在下次访问时显示欢迎信息

方法:

bash 复制代码
def set_cookie(request):
    response = render(request, 'set_cookie.html')
    response.set_cookie('username', 'john', max_age=3600)# 设置一个名为username,值为john的cookie,有效期为3600秒
    return response

def get_cookie(request):
    username = request.COOKIES.get('username', 'guest')
    return HttpResponse(f"欢迎回来,{username}!")

路由:

bash 复制代码
path('set_cookie', views.set_cookie, name='set_cookie'),
path('get_cookie', views.get_cookie, name='get_cookie'),

html:

bash 复制代码
<Doctype html>
<html>
<head>
	<title>Set Cookie</title>
</head>
<body>
	<h1>Set Cookie</h1>
	<p>Cookie set successfully!</p
</body>
</html>

访问链接http://127.0.0.1:8000/article/set_cookie设置cookie

在访问http://127.0.0.1:8000/article/get_cookie获取cookie

二、Django 中 Session

假设你想在用户登录后存储他们的登录状态

方法:

bash 复制代码
def login_view(request):
    if request.method == 'POST':
        request.session['is_login'] = True
        return redirect('/article/index_view')
    else:
        return render(request, 'login_view.html')

def index_view(request):
    if 'is_login' in request.session:
        return render(request, 'index_view.html')
    else:
        return redirect('/article/login_view')

def logout_view(request):
    request.session.clear()
    return redirect('/article/login_view')

路由:

bash 复制代码
path('login_view', views.login_view, name='login_view'),
path('logout_view', views.logout_view, name='logout_view'),
path('index_view', views.index_view, name='index_view'),

login_view.html:

bash 复制代码
<DOCTYPE html>
<html>
<head>
	<title>Login</title>
</head>
<body>
	<h1>Login</h1>
	<form method="post" action="">
		{% csrf_token %}
		<label for="username">Username:</label>
		<input type="text" id="username" name="username" required><br><br>
		<label for="password">Password:</label>
		<input type="password" id="password" name="password" required><br><br>
		<input type="submit" value="Login">
	</form>
</body>
</html>

index_view.html:

bash 复制代码
<DOCTYPE html>
<html>
<head>
	<title>Welcome to our website</title>
</head>
<body>
	<h1>Welcome to our website</h1>
	<p>Thank you for visiting our website. We hope you find what you are looking for.</p>
    <span><a href="/article/logout_view">logout</a></span>
</body>
</html>

访问链接http://127.0.0.1:8000/article/login_view

因为这里只是介绍session,所以没有做验证用户处理

点击logout之后

三.区别

Cookie: 适合存储小量且不敏感的信息,直接由用户浏览器管理

Session: 适合存储较大的数据和敏感信息,数据保存在服务器端,更安全

注意: django.session 表中保存的是浏览器的信息,而不是每一个用户的信息

因此,同一浏览器多个用户请求只保存一条记录(后面覆盖前面),多个浏览器请求才保存多条记录

相关推荐
2301_8038756112 小时前
PHP 中处理会话数组时的类型错误解析与修复指南
jvm·数据库·python
m0_7436239212 小时前
c++如何批量修改文件后缀名_std--filesystem--replace_extension【实战】
jvm·数据库·python
2501_9142459313 小时前
CSS如何处理CSS变量作用域冲突_利用特定类名重写变量值
jvm·数据库·python
菜鸟学Python13 小时前
Python生态在悄悄改变:FastAPI全面反超,Django和Flask还行吗?
开发语言·python·django·flask·fastapi
maqr_11014 小时前
MySQL数据库迁移到云端如何保障安全_数据加密与SSL连接配置
jvm·数据库·python
u01091476015 小时前
MySQL如何限制触发器递归调用的深度_防止触发器死循环方法
jvm·数据库·python
weixin_3812881815 小时前
MySQL中如何使用HEX函数转换十六进制_MySQL进制转换函数
jvm·数据库·python
Deitymoon15 小时前
嵌入式数据库——SQLite基础
数据库·sqlite
YMatrix 官方技术社区15 小时前
美国·硅谷|YMatrix 即将亮相 Postgres Conference 2026,前瞻 AI 时代的数据基座
数据库·数据仓库·postgresql·时序数据库·ymatrix
bKYP953cL15 小时前
构建自己的AI编程助手:基于RAG的上下文感知实现方案
数据库·人工智能·ai编程