19)django-cookie使用
Cookie,有时也用其复数形式 Cookies,指某些网站为了辨别用户身份、进行 session 跟踪而储存在用户本地终端上的数据(通常经过加密)
一:cookie
cookie在客户端浏览器的是以一个文件形式存在。
二:cookie生存周期(原理)
客户端向服务器发起请求
==》服务器要求验证
==》客户端输入用户名和密码
==》服务器验证,验证成功后,推送一串字符串给客户端,如{'is_login':'aaaaaaaaadddffffffd'}表示客户端已登录过。
==>客户端保存这个串,下次客户端在来的时候,就不需要输入用户名和密码,
让客户端向服务器提供这一串。如果一致就是登录成功。上面提供的串就是cookie
三:cookie获取和设置
1)在服务器上获取cookie
服务器的cookie包含在request里面
name=request.COOKIES获取
备注:request里面的cookie是客户端浏览器传递过来的。所以可以通过浏览设置其他cookie(JS或者jquery设置)
request.COOKIES 用户发来数据时候带的所有cookie,就是字典
request.COOKIES.get("name")
2)在服务器上设置cookie
response=render(request,"index.html")
这个respone可以设置cookie,return的时候会一起发给客户端
response=render(request,"index.html")
response=redirect("/index/") response.set_cookie("key,"value") #要设置cookie,只要不关闭浏览器一直生效,如果关闭就失效
3)设置cookie加密解密
上面的cookie是明文的
加密
obj=render(request,"index.html")
obj.set_signed_cookie("username",salt="adsf") 加密
解密
request.get_signed_cookie("username",salt="adsf")
4)cookie其他参数
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获取(不是绝对,底层抓包可以获取到也可以被覆盖)
response.set_cookie("key,"value",max_age=10) #10秒过期 currnet_data=datetime.datetime.utcnow()
currnet_data=currnet_data+10
response.set_cookie("key,"value",expires=currnet_data)#表示到什么时候点到期 cookie可以做两周,其他其他时间免登陆
5)cookie结合装饰器可以实现所用功能都需要登录验证
装饰器验证分为FBV和CBV(CBV装饰有三种方法)
# 装饰器实现用户认证 #FBV装饰器
def auth(func):
def inner(request,*args,**kwargs):
v=request.COOKIES.get("username111")
if not v:
return redirect("/login/")
return func(request,*args,**kwargs)
return innner
#CDB装饰器(3种方法) def auth(func):
def inner(request,*args,**kwargs):
v=request.COOKIES.get("username111")
if not v:
return redirect("/login/")
return func(request,*args,**kwargs)
return inner from django import views
#djanog装饰器
from django.utils.decorators import method_decorator
#装饰方式3
@method_decorator(auth,name="dispatch")#装饰类里的dispatch
class Auth(views.View): #装饰方式2,这个方法还是嫌烦可以用方式3
@method_decorator(auth)
def dispatch(self, request, *args, **kwargs):
return super(Auth,self).dispatch(request, *args, **kwargs) #装饰方式1
#@method_decorator(auth) #这里只对get登陆验证,如果post等其他也要加,那每个都要加,所以可以用dispath
def get(self,request):
v=request.COOKIES.get("username111") return render(request,"index.html",{"current_user":v})
def post(self,request):
v=request.COOKIES.get("username111")
return render(request,"index.html",{"current_user":v})
四:示例
实现功能
1)用户登陆设置获取cookie
2)设置免登录时间
3)设置其他页面必须要登录验证
4)通过cookie实现值在其他页面展示,比如:name
settings.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login$',views.login,name="login"),
url(r'^index$',views.index,name="index"),
url(r'^auth',views.auth,name="auth"),
url(r'^Auth',views.Auth.as_view()),
]
views.py
from django.shortcuts import render,redirect,HttpResponse # Create your views here. def auth(func):
def inner(request,*args,**kwargs):
v=request.COOKIES.get("name")
if not v:
return redirect("/login")
return func(request,*args,**kwargs)
return inner #对CBV类实现装饰验证
from django import views
#djanog装饰器
from django.utils.decorators import method_decorator
#装饰方式3
@method_decorator(auth,name="dispatch")
class Auth(views.View): #装饰方式2,这个方法还是嫌烦可以用方式3
@method_decorator(auth)
def dispatch(self, request, *args, **kwargs):
return super(Auth,self).dispatch(request, *args, **kwargs) #装饰方式1
#@method_decorator(auth) #这里只对get登陆验证,如果post等其他也要加,那每个都要加,所以可以用dispath
def get(self,request):
v=request.COOKIES.get("name") return render(request,"index.html",{"name":v})
def post(self,request):
v=request.COOKIES.get("name")
return render(request,"index.html",{"name":v}) def login(request):
if request.method=="GET":
return render(request,"login.html")
if request.method=="POST":
u=request.POST.get("username")
p=request.POST.get("password")
if u=="root" and p=="":
response=redirect("/index")
#服务器给客户端设置cookie:name,并设置cookie 10秒后失效,只对index生效
#response.set_cookie("name","alex",10)
#设置登陆超时
t=request.POST.get("setCookietime")
max_t=int(t)*24*60*60#设置多少天超时
response.set_cookie("name","root",max_age=max_t,path="/index")
return response
else:
return redirect("/login") @auth#装饰用户必须要登陆验证
def index(request):
if request.method=="GET":
#客户端获取cookie设置的name
name=request.COOKIES.get("name")
return render(request,"index.html",{"name":name})
模板:
login.html <form action="{% url "login" %}" method="post">
<fieldset>
<legend>登陆</legend>
<p>
<label for="username">用户名:</label>
<input type="text" id="username" name="username">
</p>
<p>
<label for="password">密 码:</label>
<input type="password" id="password" name="password">
</p>
<p>
<select name="setCookietime"> <!-- -->
<option value="10">10天</option>
<option value="20">20天</option>
</select>天免登录
<input type="submit" value="提交"> </p> </fieldset>
</form> index.html <body>
<h1>欢迎{{ name }}登陆</h1>
</body>
设置免登录cookie状态
19)django-cookie使用的更多相关文章
- Django cookie相关操作
Django cookie 的相关操作还是比较简单的 首先是存储cookie #定义设置cookie(储存) def save_cookie(request): #定义回应 response = Ht ...
- falsk 与 django cookie和session存、取、删的区别
falsk cookie的存取删需导入from flask import Flask,make_response,request# 存COOKIE的方法@app.route('/setcookie') ...
- django cookie、session
Cookie.Session简介: Cookie.Session是一种会话跟踪技术,因为http请求都是无协议的,无法记录上一次请求的状态,所以需要cookie来完成会话跟踪,Seesion的底层是由 ...
- 3/19 Django框架 url路由配置及模板渲染
3/19 Django框架 url路由配置及模板渲染 1.路由分配 URL(Uniform Resoure Locato):统一资源定位符是对可以从互联网上得到的资源的位置和访问方法的一种简洁的表示, ...
- Python 19 Django 详解
本节概要 Django详解 前言 有一部分原因是,确实djando的课程有点多:并且,最近又在研究利用python做数据分析时间上耽误了.所以楼主讲所有的课程全部重新观看了一遍,再来撰写博客,其实说起 ...
- Python之路-(Django(Cookie、分页))
Cookie 分页 1.获取Cookie: request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, sal ...
- Django Cookie 和 Sessions 应用
在Django里面,使用Cookie和Session看起来好像是一样的,使用的方式都是request.COOKIES[XXX]和request.session[XXX],其中XXX是您想要取得的东西的 ...
- Python Web框架篇:Django cookie和session
part 1 概念 在Django里面,cookie和session都记录了客户端的某种状态,用来跟踪用户访问网站的整个回话. 两者最大的区别是cookie的信息是存放在浏览器客户端的,而sessio ...
- 28.Django cookie
概述 1.获取cookie request.COOKIES['key'] request.COOKIES.get('key') request.get_signed_cookie(key, defau ...
- 5.Django cookie
概述 1.获取cookie request.COOKIES['key'] request.COOKIES.get('key') request.get_signed_cookie(key, defau ...
随机推荐
- Spring 快速开始 启动Spring
[启动Spring必须配置] [web.xml部署描述符方式] 1.配置Servlet级别上下文 <servlet> <servlet-name>springDispatche ...
- 【bzoj4530】[Bjoi2014]大融合 LCT维护子树信息
题目描述 小强要在N个孤立的星球上建立起一套通信系统.这套通信系统就是连接N个点的一个树. 这个树的边是一条一条添加上去的.在某个时刻,一条边的负载就是它所在的当前能够联通的树上路过它的简单路径的数量 ...
- 'webpack'提示 不是内部或外部命令
使用webpack命令行,报错:'webpack' 不是内部或外部命令,也不是可运行的程序 或批处理文件. 解决办法: 卸载nodejs,按照默认设置从新安装一遍 Nodejs 转载:https:// ...
- 用PHP来获取access_token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".A ...
- Educational Codeforces Round 47 (Rated for Div. 2)E.Intercity Travelling
题目链接 大意:一段旅途长度N,中间可能存在N-1个休息站,连续走k长度时,疲劳值为a1+a2+...+aka_1+a_2+...+a_ka1+a2+...+ak,休息后a1a_1a1开始计, ...
- Debian9 使用 Docker 安装 gitlab完整过程
一. 安装Docker CE (参考 官网指南) 1. 卸载老版本 sudo apt-get remove docker docker-engine docker.io 2. Update the ...
- pytroch 0.3 到 0.4版本迁移资料mark
搜了一堆,还是官方资料给力,一份中文,一份英文,maek一下 https://www.pytorchtutorial.com/pytorch-0-4-0-migration-guide/ https: ...
- BIM 开发商 --广州
BIM 开发或咨询商 --广州: 1.广州君和信息技术有限公司(与二公司有合作,推荐!) 艾三维软件 www.i3vsoft.com 广州市越秀区东风中路445号越秀城市广场北塔2007 是一家为 ...
- PEP 530 -- 异步推导式
PEP 530 -- 异步推导式 摘要 PEP 492和PEP 525使用async/await语法引入了协程.PEP 530建议添加list,set,dict推导式和生成器推导式的异步版本. 理论和 ...
- 普通函数跟箭头函数中this的指向问题
箭头函数和普通函数的区别如下. 普通函数:根据调用我的人(谁调用我,我的this就指向谁) 箭头函数:根据所在的环境(我再哪个环境中,this就指向谁) 一针见血式总结: 普通函数中的this: 1. ...