Django项目之cookie+session

原文: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('1234567',username,max_age=10)
            return obj
        else:
            return render(request, 'login.html',{'msg':'用户名或密码错误'})

def index(request):
v
= request.COOKIES.get('1234567') 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="0">
<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')
装饰器

 

posted @ 2018-09-06 12:10  一只奔跑的乌龟  阅读(192)  评论(0编辑  收藏  举报