django基础-cookie和session
Cookie是什么?
保存在客户端浏览器上的键值对。
http是短连接,无状态的,用户通过浏览器访问服务端如果登录成功,
服务端会给客户端浏览器发送一个cookie,下次再来访问时只要携带者cookie就不需要再次进行登录。
cookie的增删改查
获取cookie:
request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None) 参数: default: 默认值 salt: 加密盐 max_age: 后台控制过期时间
设置cookie:
rep = HttpResponse(...) 或 rep = render(request, ...) rep.set_cookie(key,value,...) rep.set_signed_cookie(key,value,salt='加密盐',...) 参数: key, 键 value='', 值 max_age=None, 超时时间 expires=None, 超时时间(IE requires expires, so set it if hasn't been already.) path='/', Cookie生效的路径,/ 表示根路径,特殊的:跟路径的cookie可以被任何url的页面访问 domain=None, Cookie生效的域名 secure=False, https传输 httponly=False 只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖)
$.cookie(
"list_pager_num"
,
30
,{ path:
'/'
});
cookie的功能、优点和应用
协助session处理登陆
Session是什么?
保存在服务端的数据(本质是键值对)
{
“asdfasdfasdfasdfasdf":{'id':1,'name':'傻子',email='xxxx'}
asdffffsdfdfdfdfd":{'id':2,'name':'啥子',email='xxxx'}
sdfsdf":{'id':2,'name':'啥子',email='xxxx'}
}
session配置
- 存储位置
Django默认支持Session,并且默认是将Session数据存储在数据库中,即:django_session 表中。
- 配置文件settings.py
SESSION_ENGINE = 'django.contrib.sessions.backends.db' # 引擎(默认) SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串(默认) SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径(默认) SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名(默认) SESSION_COOKIE_SECURE = False # 是否Https传输cookie(默认) SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输(默认) SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周)(默认) SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期(默认) SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存(默认)
- 超时时间、每次刷新更新时间
session增删改查
- 增删改查
- 获取随机字符串
- 主动设置超时时间
def index(request): # 获取、设置、删除Session中数据 request.session['k1'] request.session.get('k1',None) request.session['k1'] = 123 request.session.setdefault('k1',123) # 存在则不设置 del request.session['k1'] # 所有 键、值、键值对 request.session.keys() request.session.values() request.session.items() request.session.iterkeys() request.session.itervalues() request.session.iteritems() # 用户session的随机字符串 request.session.session_key # 将所有Session失效日期小于当前日期的数据删除 request.session.clear_expired() # 检查 用户session的随机字符串 在数据库中是否 request.session.exists("session_key") # 删除当前用户的所有Session数据 request.session.delete("session_key") request.session.set_expiry(value) * 如果value是个整数,session会在些秒数后失效。 * 如果value是个datatime或timedelta,session就会在这个时间后失效。 * 如果value是0,用户关闭浏览器session就会失效。 * 如果value是None,session会依赖全局session失效策略。
session缓存、数据库和文件
缓存session:settings.py
SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # 引擎 SESSION_CACHE_ALIAS = 'default' # 使用的缓存别名(默认内存缓存,也可以是memcache),此处别名依赖缓存的设置 SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串 SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径 SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名 SESSION_COOKIE_SECURE = False # 是否Https传输cookie SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输 SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周) SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期 SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存
文件session:settings.py
SESSION_ENGINE = 'django.contrib.sessions.backends.file' # 引擎 SESSION_FILE_PATH = None # 缓存文件路径,如果为None,则使用tempfile模块获取一个临时地址tempfile.gettempdir() # 如:/var/folders/d3/j9tj0gz93dg06bmwxmhh6_xm0000gn/T SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串 SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径 SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名 SESSION_COOKIE_SECURE = False # 是否Https传输cookie SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输 SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周) SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期 SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存
Session缓存+数据库:settings.py
数据库用于做持久化,缓存用于提高效率,
缓存
+
数据库 先是缓存中查找,没有就去数据库中查找
SESSION_ENGINE
=
'django.contrib.sessions.backends.cached_db'
# 引擎
Cookie 中存放Session:settings.py
这样的存放方式 相当于没有使用Session
SESSION_ENGINE
=
'django.contrib.sessions.backends.signed_cookies'
# 引擎
Session的功能、优点和应用
功能:保持会话(Web网站)
优点:敏感信息不会直接给客户端
应用:依赖cookie,比如用户登陆
案例:做一个很简单相亲网
需求:
1. 登录,基于Session,装饰器
2. 数据表:
男生表:
id username password
女生表
id username password
男生女生关系表:
id nid nid
3. 功能:
登录页:
用户名:
密码:
性别:
一周免登录:checkbox
session[id]
session[sex]
查看异性列表:
session[sex]
查看与自己有关系的异性姓名列表
用户登录
如果男用户登录,显示女生列表
如果女用户登录,显示男生列表
1 ===========================urls=========================================================== 2 3 """s4day74 URL Configuration 4 5 The `urlpatterns` list routes URLs to views. For more information please see: 6 https://docs.djangoproject.com/en/1.11/topics/http/urls/ 7 Examples: 8 Function views 9 1. Add an import: from my_app import views 10 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 11 Class-based views 12 1. Add an import: from other_app.views import Home 13 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 14 Including another URLconf 15 1. Import the include() function: from django.conf.urls import url, include 16 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 17 """ from django.conf.urls import url 18 from django.contrib import admin 19 from app01.views1 import love 20 from app01.views1 import account 21 urlpatterns = [ 22 url(r'^admin/', admin.site.urls), 23 # url(r'^test.html$',views.test), # url(r'^login/', views.login), # url(r'^index/', views.index), # url(r'^test.html$', love.test), url(r'^login.html$', account.login), 24 url(r'^index.html$', love.index), 25 url(r'^logout.html$', account.logout), 26 url(r'^others.html$', love.others), 27 28 ]
1 =============================models=============================================== 2 from django.db import models 3 4 # Create your models here. # class UserInfo(models.Model): class Boy(models.Model): 5 nickname = models.CharField(max_length=32) 6 username = models.CharField(max_length=32) 7 password = models.CharField(max_length=64) 8 9 class Girl(models.Model): 10 nickname = models.CharField(max_length=32) 11 username = models.CharField(max_length=32) 12 password = models.CharField(max_length=64) 13 14 15 class B2G(models.Model): 16 b = models.ForeignKey(to="Boy",to_field="id") 17 g = models.ForeignKey(to="Girl",to_field="id")
1 =============================account.py===============================================<br>from django.shortcuts import render,HttpResponse,redirect 2 from app01 import models 3 4 5 def login(request): 6 if request.method == "GET": 7 return render(request, 'login.html') 8 9 else: 10 user=request.POST.get("username") 11 pwd=request.POST.get("password") 12 gender=request.POST.get("gender") 13 rmb=request.POST.get("rmb") 14 #性别判断 if gender=="1": 15 obj=models.Boy.objects.filter(username=user,password=pwd).first() 16 else: 17 obj=models.Girl.objects.filter(username=user,password=pwd).first() 18 if not obj: 19 return render(request, "login.html", {"msg": "用户名或密码错误"}) 20 21 else: 22 #session里面设置值,可以嵌套 相当于归类 一个key对应一条条信息 # request.session['user_id']=obj.id # request.session["gender"]=gender # request.session["username"]=user if rmb: 23 request.session.set_expiry(15) 24 request.session['user_info']={'user_id':obj.id,'gender':gender,'username':user,'nickname':obj.nickname} 25 return redirect("/index.html") #跳到后台管理 def logout(request): 26 if request.session.get("user_info"): 27 request.session.clear() 28 return redirect('/login.html')
1 ============================= love.py===============================================<br>from django.shortcuts import render,HttpResponse,redirect 2 from app01 import models 3 from utils.pager import PageInfo 4 5 def index(request): 6 if not request.session.get("user_info"): 7 return redirect("/login.html") 8 else: 9 #到session里面获取性别 10 gender=request.session.get("user_info").get('gender') 11 if gender == "1": 12 # user_list=models.Girl.objects.all() 13 all_count = models.Girl.objects.all().count() 14 page_info = PageInfo(request.GET.get('page'), all_count, 10, '/boy.html', 11) 15 user_list = models.Girl.objects.all()[page_info.start():page_info.end()] 16 return render(request, 'index.html', {'user_list': user_list, 'page_info': page_info}) 17 else: 18 # user_list=models.Boy.objects.all() 19 all_count = models.Boy.objects.all().count() 20 page_info = PageInfo(request.GET.get('page'), all_count, 10, '/boy.html', 11) 21 user_list = models.Boy.objects.all()[page_info.start():page_info.end()] 22 return render(request, 'index.html', {'user_list': user_list, 'page_info': page_info}) 23 24 # return render(request,"index.html",{'user_list':user_list}) 25 26 27 28 def others(request): 29 """ 30 获取与当前用户有关的异形 31 :param request: 32 :return: 33 """ 34 current_user_id=request.session.get('user_info').get("user_id") 35 gender=request.session.get("user_info").get("gender") 36 if gender == "1": 37 user_list=models.B2G.objects.filter(b_id=current_user_id).values('g__nickname') 38 else: 39 user_list=models.B2G.objects.filter(g_id=current_user_id).values('b__nickname') 40 return render(request,'others.html',{'user_list':user_list})
1 ============================= login.html===============================================<br><!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 {% include 'user_header.html' %} 9 <h1>有关系的异性列表</h1> 10 <ul> 11 {% for row in user_list%} 12 {% if row.g__nickname %} 13 <li>{{ row.g__nickname }}</li> 14 {% else %} 15 <li>{{ row.b__nickname }}</li> 16 {% endif %} 17 {% endfor %} 18 </ul> 19 </body> 20 </html>
1 ============================= index.html===================================================================================================================<br>!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css"> </head> <body> 2 {# <h2>当前用户:{{ request.session.user_info.nickname }}</h2>#} {# <a href="/logout.html">注销</a>#} {% include 'user_header.html' %} 3 <h3>异性列表</h3> <a href="/others.html">查看和我有关的异形</a> <table class="table table-striped table-bordered table table-hover table table-condensed"> <tr> <th>ID</th> <th>姓名</th> <th>密码</th> </tr> 4 {% for row in user_list %} 5 <tr> <td>{{ row.id }}</td> <td>{{ row.nickname }}</td> <td>{{ row.password }}</td> </tr> 6 {% endfor %} 7 8 </table> <nav aria-label="Page navigation"> <ul class="pagination"> 9 {{ page_info.pager|safe }} 10 </ul> </nav> </body> </html>
1 ============================= others.html====================================<br><!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 {% include 'user_header.html' %} 9 <h1>有关系的异性列表</h1> 10 <ul> 11 {% for row in user_list%} 12 {% if row.g__nickname %} 13 <li>{{ row.g__nickname }}</li> 14 {% else %} 15 <li>{{ row.b__nickname }}</li> 16 {% endif %} 17 {% endfor %} 18 </ul> 19 </body>
1 <h2>当前用户:{{ request.session.user_info.nickname }}</h2> <a href="/logout.html">注销</a>