网站开发后端用什么,平台网站的建设需求,施工企业机械承包责任制度,网亿(深圳)信息科技有限公司文章目录 前言CookieSession 一、Django 中 Cookie二、Django 中 Session三.区别 前言
Cookie
Cookie 是由服务器发送到用户浏览器的小文件#xff0c;用于存储用户的相关信息。每次用户访问网站时#xff0c;浏览器会将这些 cookie 发送回服务器
特点:
1. 数据存储在客户… 文章目录 前言CookieSession 一、Django 中 Cookie二、Django 中 Session三.区别 前言
Cookie
Cookie 是由服务器发送到用户浏览器的小文件用于存储用户的相关信息。每次用户访问网站时浏览器会将这些 cookie 发送回服务器
特点:
1. 数据存储在客户端大小通常限制在 4KB
2. 过期时间可以设置默认是会话级别
3. 用户可以手动删除 cookieSession
Session 是一种在服务器端存储用户数据的机制用户的数据以会话的方式保存。Django 会为每个用户生成一个唯一的 session ID并将其存储在客户端的 cookie 中
特点:
1. 数据存储在服务器端可以存储更大和复杂的数据结构
2. 更安全因为用户不能直接访问 session 数据
3. 自动管理会话的过期时间一、Django 中 Cookie
假设你想在用户的浏览器中存储一个用户的用户名以便在下次访问时显示欢迎信息
方法
def set_cookie(request):response render(request, set_cookie.html)response.set_cookie(username, john, max_age3600)# 设置一个名为username值为john的cookie有效期为3600秒return responsedef get_cookie(request):username request.COOKIES.get(username, guest)return HttpResponse(f欢迎回来{username})路由
path(set_cookie, views.set_cookie, nameset_cookie),
path(get_cookie, views.get_cookie, nameget_cookie),html
Doctype html
html
headtitleSet Cookie/title
/head
bodyh1Set Cookie/h1pCookie 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
假设你想在用户登录后存储他们的登录状态
方法
def login_view(request):if request.method POST:request.session[is_login] Truereturn 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)路由
path(login_view, views.login_view, namelogin_view),
path(logout_view, views.logout_view, namelogout_view),
path(index_view, views.index_view, nameindex_view),login_view.html
DOCTYPE html
html
headtitleLogin/title
/head
bodyh1Login/h1form methodpost action{% csrf_token %}label forusernameUsername:/labelinput typetext idusername nameusername requiredbrbrlabel forpasswordPassword:/labelinput typepassword idpassword namepassword requiredbrbrinput typesubmit valueLogin/form
/body
/htmlindex_view.html
DOCTYPE html
html
headtitleWelcome to our website/title
/head
bodyh1Welcome to our website/h1pThank you for visiting our website. We hope you find what you are looking for./pspana href/article/logout_viewlogout/a/span
/body
/html访问链接http://127.0.0.1:8000/article/login_view 因为这里只是介绍session所以没有做验证用户处理 点击logout之后
三.区别
Cookie: 适合存储小量且不敏感的信息直接由用户浏览器管理 Session: 适合存储较大的数据和敏感信息数据保存在服务器端更安全
注意: django.session 表中保存的是浏览器的信息而不是每一个用户的信息 因此同一浏览器多个用户请求只保存一条记录后面覆盖前面,多个浏览器请求才保存多条记录