原文:https://www.cnblogs.com/sss4/p/7071334.html

HTTP协议 是短连接、且状态的,所以在客户端向服务端发起请求后,服务端在响应头 加入cokie响应给浏览器,以此记录客户端状态;

cook是来自服务端,保存在浏览器的键值对,主要应用于用户登录;

cookie如此重要!!那么如何在Django应用cookie呢?cookie又有什么缺陷呢?

一、Django应用cookie

参数介绍

1、max_age=1 :cookie生效的时间,单位是秒

2、expires:具体过期日期  

3、path='/':指定那个url可以访问到cookie;‘/’是所有; path='/'

4、 domain=None(None代表当前域名):指定那个域名以及它下面的二级域名(子域名)可以访问这个cookie

5、secure=False:https安全相关

6、httponly=False:限制只能通过http传输,JS无法在传输中获取和修改

设置cookie

1.普通

obj.set_cookie("tile","zhanggen",expires=value,path='/' )

2.加盐

普通cookie是明文传输的,可以直接在客户端直接打开,所以需要加盐,解盐之后才能查看

obj.set_signed_cookie('k','v',salt="zhangge")

获取cookie

1、普通

request.COOKIES.get(‘k’)

2、加盐

cookies=request.get_signed_cookie('k',salt='zhanggen')

cookie之登录应用

1.简单应用:longin界面和index界面,访问index界面先判断是否登录,若登录可以访问,若未登录跳转到登录界面。

【代码】

#settings.py文件 :设置静态文件路径,将css样式放到该路径中

STATIC_URL = '/static/'

STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
) #urls.py文件:设置url路由 urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^identify/', views.identify),
url(r'^login/', views.login),
url(r'^index/', views.index),
] #views.py文件 def login(request):
if request.method == "GET":
return render(request,'login.html',{'msg':''})
elif request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if username == 'lijun25' and password == 'lijun25':
obj = redirect('/index/')
obj.set_cookie('',username,max_age=10)
return obj
else:
return render(request, 'login.html',{'msg':'用户名或密码错误'}) def index(request):
v = request.COOKIES.get('')
print v
if v:
return render(request, 'index.html')
else:
return redirect('/login/')
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="">
<title>后台管理</title>
<link href="/static/login.css" rel="stylesheet" type="text/css" /> </head> <body>
<div class="login_box">
<div class="login_l_img"><img src="/static/images/login-img.png" /></div>
<div class="login">
<div class="login_logo"><a href="#"><img src="/static/images/login_logo.png" /></a></div>
<div class="login_name">
<p>后台管理系统</p>
</div>
<form method="post">
<input name="username" type="text" value="用户名" onfocus="this.value=''" onblur="if(this.value==''){this.value='用户名'}">
<span id="password_text" onclick="this.style.display='none';document.getElementById('password').style.display='block';document.getElementById('password').focus().select();" >密码</span>
<input name="password" type="password" id="password" style="display:none;" onblur="if(this.value==''){document.getElementById('password_text').style.display='block';this.style.display='none'};"/>
<input value="登录" style="width:100%;" type="submit">
<div color="red" align="center">{{ msg }}</div>
</form>
</div>
</div>
<div style="text-align:center;">
</div>
</body>
</html>

login.html

【验证】

登录成功后可以看到浏览器上的定义的一对键值,会跳转到index页面,过10s钟后再cookies会失效,刷新会返回到登录界面重新认证

2.进阶应用:以上这样cookies是明文的,很不安全

#views.py

def login(request):
if request.method == "GET":
return render(request,'login.html',{'msg':''})
elif request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if username == 'lijun25' and password == 'lijun25':
obj = redirect('/index/')
# obj.set_cookie('k',username,max_age=10,)
obj.set_signed_cookie('k','v',salt='auto',max_age=10)
return obj
else:
return render(request, 'login.html',{'msg':'用户名或密码错误'}) def index(request):
    # cookie = request.COOKIES.get('k')
    try:
        cookie = request.get_signed_cookie('k',salt='auto')
        print cookie
        return render(request, 'index.html')
    except:
        return redirect('/login/')

【验证】

第一次访问Djanao程序会给浏览器一对键值对(Response Cookies),是加盐的,在一次访问Request Cookies里会带着这对键值对给Django程序。

3.继续进阶应用,若views函数后续持续增加,那么就需要在每个视图函数前加入cookie认证,代码重复,在不修改源代码和不修改调用方式的前提下,这时候就需要用装饰器了

def cookie_auth(func):
def weaper(request,*args,**kwargs):
#cookies = request.get_signed_cookie('k', salt='zhanggen')
try:
cookie = request.get_signed_cookie('k', salt='auto')
print cookie
if cookie == 'v':
return func(request)
else:
return redirect('/login/')
except:
return redirect('/login/')
return weaper def login(request):
if request.method == "GET":
return render(request,'login.html',{'msg':''})
elif request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if username == 'lijun25' and password == 'lijun25':
obj = redirect('/index/')
# obj.set_cookie('k',username,max_age=10,)
obj.set_signed_cookie('k','v',salt='auto',max_age=10)
return obj
else:
return render(request, 'login.html',{'msg':'用户名或密码错误'}) @cookie_auth
def home(request):
return HttpResponse('欢迎来得home界面') @cookie_auth
def index(request):
return render(request, 'index.html')

装饰器

Django项目之cookie+session的更多相关文章

  1. Django学习手册 - cookie / session

    cookie """ cookie属性: obj.set_cookie(key,value,....) obj.set_signed_cookie(key,value,s ...

  2. django项目搭建及Session使用

    django+session+中间件 一.使用命令行创建django项目 在指定路径下创建django项目 django-admin startproject djangocommon   在项目目录 ...

  3. Django 认证系统 cookie & session & auth模块

    概念 cookie不属于http协议范围,由于http协议无法保持状态,但实际情况,我们却又需要“保持状态”,因此cookie就是在这样一个场景下诞生. cookie的工作原理是:由服务器产生内容,浏 ...

  4. 49、django工程(cookie+session)

    49.1.介绍: 1.cookie不属于http协议范围,由于http协议无法保持状态,但实际情况,我们却又需要"保持状态",因此cookie就是在这样一个场景下诞生. cooki ...

  5. Django框架 之 Cookie和Session初识

    Django框架 之 Cookie和Session初识 浏览目录 Cookie介绍 Django中的Cookie Session 一.Cookie介绍 1.Cookie产生的意义 众所周知,HTTP协 ...

  6. Django Cookie,Session

    Cookie Cookie的由来 HTTP协议是无状态的,每次请求都是独立的,对服务器来说,每次的请求都是全新的,上一次的访问是数 据是无法保留到下一次的 某些场景需要状态数据或者中间数据等相关对下一 ...

  7. Django 中的 cookie 和 session

    一.cookie 由于HTTP协议是无状态的,而服务器端的业务必须是要有状态的.Cookie诞生的最初目的是为了存储web中的状态信息,以方便服务器端使用.比如判断用户是否是第一次访问网站.目前最新的 ...

  8. python 全栈开发,Day76(Django组件-cookie,session)

    昨日内容回顾 1 json 轻量级的数据交换格式 在python 序列化方法:json.dumps() 反序列化方法:json.loads() 在JS中: 序列化方法:JSON.stringfy() ...

  9. django框架--cookie/session

    目录 一.http协议无状态问题 二.会话跟踪技术--cookie 1.对cookie的理解 2.cookie的使用接口 3.cookie的属性 4.使用cookie的问题 三.会话跟踪技术--ses ...

随机推荐

  1. Spring源码学习:DefaultAopProxyFactory

    /* * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Vers ...

  2. formidable模块的使用

    Node.js的Formidable模块的使用   今天总结了下Node.js的Formidable模块的使用,下面做一些简要的说明. 1)     创建Formidable.IncomingForm ...

  3. FuelPHP 系列(四) ------ Validate 验证

    一.可用规则: 1.required 不能为 null, false or empty string.: 2.required_with 关联某个字段,关联字段有值则该字段必须有值: 3.match_ ...

  4. 消息队列1:RabbitMQ解析并基于Springboot实战

    RabbitMQ简介 AMQP:Advanced Message Queue,高级消息队列协议.它是应用层协议的一个开放标准,为面向消息的中间件设计,基于此协议的客户端与消息中间件可传递消息,并不受产 ...

  5. mac 关闭显示器 & 快捷键

    mac 关闭显示器 & 快捷键 https://support.apple.com/zh-cn/HT201236 https://support.apple.com/zh-cn/HT20705 ...

  6. maven测试时中文乱码问题解决方法

    pom.xml增加-Dfile.encoding=UTF-8配置,如下: <plugin> <!--升级到新版本解决控制台乱码问题--> <groupId>org. ...

  7. #LOJ2564 SDOI2018 原题识别 主席树

    转载请注明原文地址:http://www.cnblogs.com/LadyLex/p/9057297.html 原题链接: 今天考试考了前天的SDOI考题 天啊我菜爆,只有T2拿了30分 然后考试后半 ...

  8. 【洛谷P4955 】[USACO14JAN]越野滑雪越野滑雪

    题目链接:ヾ(≧∇≦*)ゝ 对于每一个点可以向它右边的点和下面的点连边,权值就为两个点的高度差 然后再把所有的边按边权从小到大排序,并查集加点 最后判断当前集合是否涵盖所有的航点,如果是,就输出最后一 ...

  9. 生成器 yield

    由于生成器的其中一种创建方式与列表推导式很相似,这里先说一下列表推导式. 列表推导式 列表推导式又叫列表生成式,官方叫做 list comprehension.顾名思义,这个是用来生成列表的. 用法: ...

  10. SSM框架的搭建与测试

    关于框架的搭建无非就是 框架所依赖的jar包,然后就是关于各个框架的配置文件: 下面我们来看下不同层的依赖的jar包以及各个配置文件: 首先pojo这一层只需要依赖parent聚合工程 mapper层 ...