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使用的更多相关文章

  1. Django cookie相关操作

    Django cookie 的相关操作还是比较简单的 首先是存储cookie #定义设置cookie(储存) def save_cookie(request): #定义回应 response = Ht ...

  2. falsk 与 django cookie和session存、取、删的区别

    falsk cookie的存取删需导入from flask import Flask,make_response,request# 存COOKIE的方法@app.route('/setcookie') ...

  3. django cookie、session

    Cookie.Session简介: Cookie.Session是一种会话跟踪技术,因为http请求都是无协议的,无法记录上一次请求的状态,所以需要cookie来完成会话跟踪,Seesion的底层是由 ...

  4. 3/19 Django框架 url路由配置及模板渲染

    3/19 Django框架 url路由配置及模板渲染 1.路由分配 URL(Uniform Resoure Locato):统一资源定位符是对可以从互联网上得到的资源的位置和访问方法的一种简洁的表示, ...

  5. Python 19 Django 详解

    本节概要 Django详解 前言 有一部分原因是,确实djando的课程有点多:并且,最近又在研究利用python做数据分析时间上耽误了.所以楼主讲所有的课程全部重新观看了一遍,再来撰写博客,其实说起 ...

  6. Python之路-(Django(Cookie、分页))

    Cookie 分页 1.获取Cookie: request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, sal ...

  7. Django Cookie 和 Sessions 应用

    在Django里面,使用Cookie和Session看起来好像是一样的,使用的方式都是request.COOKIES[XXX]和request.session[XXX],其中XXX是您想要取得的东西的 ...

  8. Python Web框架篇:Django cookie和session

    part 1 概念 在Django里面,cookie和session都记录了客户端的某种状态,用来跟踪用户访问网站的整个回话. 两者最大的区别是cookie的信息是存放在浏览器客户端的,而sessio ...

  9. 28.Django cookie

    概述 1.获取cookie request.COOKIES['key'] request.COOKIES.get('key') request.get_signed_cookie(key, defau ...

  10. 5.Django cookie

    概述 1.获取cookie request.COOKIES['key'] request.COOKIES.get('key') request.get_signed_cookie(key, defau ...

随机推荐

  1. glide:4.7.1 与 26.1.0冲突

    implementation 'com.android.support:support-v4:26.1.0'implementation 'com.github.bumptech.glide:glid ...

  2. Sqlserver远程过程调用失败

    这种情况一般是由于有高版本的SqlServer导致的,网上有删除Loaldb之类的建议,这样其实不太好,回头用高版本数据库的话还得装回来.其实可以通过计算机管理->服务和应用程序进行设置,用下面 ...

  3. GCC编译器原理(一)03------GCC 工具:gprof、ld、libbfd、libiberty 和libopcodes

    1.3.7 gprof:性能分析工具 参考文档:https://www.cnblogs.com/andashu/p/6378000.html gprof是GNU profile工具,可以运行于linu ...

  4. CF920E Connected Components?

    CF luogu 先讲两个靠谱的做法 1.首先因为有n个点,m条不存在的边,所以至少存在一个点,和m/n个点之间没边,所以把这个点找出来,连一下其他相连的点,这样还剩m/n个点没确定在哪个联通块,而这 ...

  5. codeforces706E

    好精妙的一道题啊 传送门:here 大致题意:有一个$ n*m$的矩阵,q次询问每次交换给定两个无交矩阵的对应元素,求操作后的最终矩阵? 数据范围:$ n,m<=1000, q<=1000 ...

  6. SFTP远程连接服务器上传下载文件-vs2010项目实例

    本项目仅测试远程连接服务器,支持上传,下载文件,更多功能开发请看API自行开发. 环境:win7系统,vs2010 vs2010项目实例下载地址:CSDN下载 如果没有CSDN积分,百度网盘下载(密码 ...

  7. [转] 指定进程运行的CPU

    转自:https://www.cnblogs.com/liuhao/archive/2012/06/21/2558069.html coolshell最新的文章<性能调优攻略>在“多核CP ...

  8. MySql delete和truncate区别

    项目 delete truncate 添加where条件 可以添加 不可以添加 执行效率 略高 高 自增长列 delete删除后,插入数据的自增长 列值从断点开始 truncate删除后,插入数据的自 ...

  9. bootstrap模态框显示时被遮罩层遮住了

    <style>.modal-backdrop{z-index:0;}</style>

  10. html5离线记事本

    离线记事本 这是一个笔记应用,不需要联网,也不需要数据库,可以直接把数据储存在本地.方便易用! ^_^ <!DOCTYPE html>  <html>  <head> ...