15 django_cookie&session
cookie&session
视图函数
1 from django.shortcuts import render, HttpResponse, redirect 2 from cs_app01.myforms import Myform 3 from cs_app01.models import UserInfo 4 import datetime 5 6 7 def cookie(request): 8 if request.method == 'POST': 9 print(request.POST) 10 form = Myform(request.POST) 11 if form.is_valid(): 12 res = redirect('/app01/index') # 设置响应对象,redirect和render的实质都是HttpResponse的类 13 res.set_cookie('user', form.cleaned_data.get('name')) # set_cookie是HttpResponsea的方法 设置cookie 14 res.set_cookie('last_login_time', datetime.datetime.now()) 15 res.set_cookie('path_cookie', 'login_path',path='/app01/login') # path 指定路径下有效 16 res.set_cookie('max_age', '60',max_age=60) # 只有max_age, 则按秒计算过期时间, 浏览器会存在本地缓存路径, 并自动删除过期cookie 17 res.set_cookie('expires_time', '16:53:40',expires=20) # expires 指定到生效的时间 18 # 只有expires, 则按照时间字符串计算过期时间, 浏览器会存在本地缓存路径, 自动删除过期cookie 19 # expires格式可以为: 1.时间格式的字符串 : " Wdy, DD-Mth-YY HH:MM:SS GMT " 2.秒数 3.datetime.datetime 对象 20 # 若 max_age和 expires 同时存在, 则默认使用 max_age 如果设置的cookie时间小于计算机时间, 浏览器则不提取cookie 21 else: 22 clean_error = form.errors.get("__all__") 23 res = render(request, 'login.html', locals()) 24 else: 25 # 数据初始化 26 ''' 27 userlis=[] 28 for i in range(1, 10): 29 userlis.append(UserInfo(name='yangxga%s'%i, pwd='123456')) 30 UserInfo.objects.bulk_create(userlis) 31 ''' 32 form = Myform() 33 res = render(request, 'login.html', locals()) 34 return res 35 36 37 def session(request): 38 if request.method == 'POST': 39 print(request.POST) 40 form = Myform(request.POST) 41 if form.is_valid(): 42 now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") 43 # 设置session 如果数据库没有这个sessionid,数据库会插入一条记录,如果有,则更新数据库记录 44 request.session['user'] = form.cleaned_data.get('name') 45 request.session['last_login_time'] = now 46 request.session['delete_test'] = 'delete_test' 47 res = redirect('/app01/index') 48 ''' 49 设置session的过程 50 if request.COOKIE.get("sessionid"): 51 更新 52 在django—session表中创建一条记录: 53 session-key session-data 54 i2yqstppfexaxy6z74e2b1sggw5j7gm2 更新数据 55 else: 56 1 生成随机字符串 i2yqstppfexaxy6z74e2b1sggw5j7gm2 57 2 response.set_cookie("sessionid",i2yqstppfexaxy6z74e2b1sggw5j7gm2) 58 3 在django—session表中创建一条记录: 59 session-key session-data 60 i2yqstppfexaxy6z74e2b1sggw5j7gm2 {"user":yangxga1,"last_login_time":"2019-08-15 21:24:55"} 61 ''' 62 else: 63 clean_error = form.errors.get("__all__") 64 res = render(request, 'login.html', locals()) 65 else: 66 # 数据初始化 67 ''' 68 userlis=[] 69 for i in range(1, 10): 70 userlis.append(UserInfo(name='yangxga%s'%i, pwd='123456')) 71 UserInfo.objects.bulk_create(userlis) 72 ''' 73 form = Myform() 74 res = render(request, 'login.html', locals()) 75 return res 76 77 78 def index(request): 79 ''' 80 # cookies 81 print(request.COOKIES) 82 user = request.COOKIES.get('user') # 获取cookies 83 last_login_time = request.COOKIES.get('last_login_time') 84 res = render(request, 'index.html', locals()) 85 # res.delete_cookie('user') # 删除cookies 86 print(request.COOKIES) 87 ''' 88 #sessions 89 # print(request.session['user']) 90 # user = request.session['user'] # 获取cookies 91 # last_login_time = request.session['last_login_time'] 92 user = request.session.get('user') # 这种方法也行,建议这种,没取到不会报错 93 last_login_time = request.session.get('last_login_time') 94 ''' 95 查找的过程 96 1 request.COOKIE.get("session") # i2yqstppfexaxy6z74e2b1sggw5j7gm2 97 2 django-session表中过滤纪录: 98 obj=django—session.objects .filter(session-key=ltv8zy1kh5lxj1if1fcs2pqwodumr45t).first() 99 3 obj.session-data.get("user") 100 ''' 101 # del request.session['delete_test'] # 删除session 102 # print(request.session.get('delete_test')) 103 res = render(request, 'index.html', locals()) 104 return res 105 106 107 def logout(request): 108 request.session.flush() # 清空当前sessionid下的session值 109 ''' 110 清空的过程 111 1 randon_str=request.COOKIE.get("sessionid") 112 2 django-session.objects.filter(session-key=randon_str).delete() 113 3 response.delete_cookie("sessionid",randon_str) 114 115 ''' 116 return redirect('/app01/session') 117 118 119 ''' 120 class HttpResponseBase: 121 def set_cookie(self, key, 键 122 value='', 值 123 max_age=None, 超长时间cookie需要延续的时间(以秒为单位)如果参数是\ None`` ,这个cookie会延续到浏览器关闭为止。 124 expires=None, 超长时间expires默认None ,cookie失效的实际日期/时间。 125 path='/', Cookie生效的路径,浏览器只会把cookie回传给带有该路径的页面,这样可以避免将 126 cookie传给站点中的其他的应用。 表示根路径,特殊的:根路径的cookie可以被任何url的页面访问 127 domain=None, Cookie生效的域名你可用这个参数来构造一个跨站cookie。如, 128 domain=".example.com"所构造的cookie对下面这些站点都是可读的: 129 www.example.com 、 www2.example.com 和an.other.sub.domain.example.com 。 130 如果该参数设置为 None ,cookie只能由设置它的站点读取。 131 secure=False, 如果设置为 True ,浏览器将通过HTTPS来回传cookie。 132 httponly=False 只能http协议传输,无法被JavaScript获取(不是绝对,底层抓包可以获取到也可以被覆盖) 133 ): pass 134 135 # settings 136 SESSION_COOKIE_NAME= "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串(默认) 137 SESSION_COOKIE_PATH= "/" # Session的cookie保存的路径(默认) 138 SESSION_COOKIE_AGE = 10 # Session的cookie失效日期(2周)(默认) 139 SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期(默认) 140 SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存(默认) 141 142 '''
forms组件
1 from django import forms 2 from django.forms import widgets 3 from django.core.exceptions import ValidationError 4 from cs_app01.models import UserInfo 5 6 7 name_widg = widgets.TextInput(attrs={'class':'form-control'}) 8 pwd_widg = widgets.PasswordInput(attrs={'class':'form-control'}) 9 class Myform(forms.Form): 10 name = forms.CharField(min_length=4, max_length=32, widget=name_widg, label="用户名") 11 pwd = forms.CharField(min_length=4, widget=pwd_widg, label="密码") 12 13 def clean_name(self): 14 val = self.cleaned_data.get('name') 15 res = UserInfo.objects.filter(name=val).exists() 16 if res: 17 return val 18 else: 19 raise ValidationError('用户名不存在!') 20 21 def clean(self): 22 name = self.cleaned_data.get('name') 23 pwd = self.cleaned_data.get('pwd') 24 print(name, pwd) 25 res = UserInfo.objects.filter(name=name, pwd=pwd).exists() 26 if res: 27 return self.cleaned_data 28 else: 29 raise ValidationError('密码不正确!')
模板index
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>index</title> 6 </head> 7 <body> 8 9 {% if user %} 10 <h3>欢迎进入系统 </h3> {{ user }} 11 <h3>您上次登陆的时间是: </h3>{{ last_login_time }} 12 <div><a href="/app01/logout" class="btn btn-danger">注销</a></div> 13 {% else %} 14 <h3>您尚未登录 </h3> 15 <div><a href="/app01/session" class="btn btn-danger">点击登陆</a></div> 16 {% endif %} 17 </body> 18 </html>
模板login
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登陆</title> <link rel="stylesheet" href="/static/bootstrap.min.css"> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h3>登陆</h3> <form action="" method="post"> {% csrf_token %} {# {{ form.as_p }}#} {% for field in form %} <div class="form-group"> <label for="">{{ field.label }}</label> {{ field }} {% if field.label == '用户名'%} <span class="pull-right" style="color: red">{{ field.errors.0 }}</span> {% else %} <span class="pull-right" style="color: red">{{ clean_error.0 }}</span> {% endif %} </div> {% endfor %} <input type="submit" value="登陆" class="btn btn-success"> </form> </div> </div> </div> </body> </html>
夕闻道不如朝闻道