原文: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. Access restriction: The type 'BASE64Decoder' is not API

    Access restriction: The type 'BASE64Decoder' is not API (restriction on required library 'C:\Program ...

  2. BOM之navigator对象和用户代理检测

    前面的话 navigator对象现在已经成为识别客户端浏览器的事实标准,navigator对象是所有支持javascript的浏览器所共有的.本文将详细介绍navigator对象和用户代理检测 属性 ...

  3. 【luogu3768】简单的数学题 欧拉函数(欧拉反演)+杜教筛

    题目描述 给出 $n$ 和 $p$ ,求 $(\sum\limits_{i=1}^n\sum\limits_{j=1}^nij\gcd(i,j))\mod p$ . $n\le 10^{10}$ . ...

  4. Python学习--------------Atm+购物车系统

    一.程序需求 模拟实现一个ATM + 购物商城程序: 1.额度 15000或自定义 2.实现购物商城,买东西加入 购物车,调用信用卡接口结账 3.可以提现,手续费5% 4.每月22号出账单,每月10号 ...

  5. Java8新特性之Stream

    原文链接:http://ifeve.com/stream/ Java8初体验(二)Stream语法详解 感谢同事[天锦]的投稿.投稿请联系 tengfei@ifeve.com上篇文章Java8初体验( ...

  6. Django_博客项目 注册用户引发 ValueError: The given username must be set

    博客项目中 注册功能在ajax 提交数据时 报错 ValueError: The given username must be set 锁定到错误点为 判定为是无法获取到 username 字段 那先 ...

  7. Fake or True(HNOI2018)

    闲话 或许有人会问博主蒟蒻:ZJOI爆0记呢? 博主太弱了,刚刚去ZJ做了个梦回来,又得马不停蹄地准备HNOI 于是就成了烂坑 不过至少比某某更强更fake的xzz的游记要好一些 其实ZJOI挺值得回 ...

  8. 【bzoj2669】 cqoi2012—局部极小值

    http://www.lydsy.com/JudgeOnline/problem.php?id=2669 (题目链接) 题意 给出一个$n*m$的整数矩阵,其中$[1,nm]$中的整数每个出现一次,有 ...

  9. 解题:EXNR #1 金拱门

    题面 大力统计题 考虑把和的平方拆开,最终就是许多对位置乘起来求和.所以考虑每对位置的贡献,对于$a_{i,j}$和$a_{k,h}(1<=i<=k<=n,1<=j<=h ...

  10. Zabbix应用七:Zabbix发送短信报警

    Zabbix利用Python脚本调用短信API发送报警信息 一.先贴出python脚本: #!/usr/bin/python # _*_ coding:utf8 _*_ import sys impo ...