Django cookie

本文深入解析了Cookie的工作原理,包括其参数含义及安全性问题。通过Python实例展示了如何在用户登录时设置Cookie,并利用装饰器简化多次验证过程,强调了避免使用汉字作为Cookie的重要性。

cookie:网站为了验证用户身份而下发的存储在用户本地终端上的数据。

基本上就是这个意思:用户向服务器发起请求,服务器下发cookie到本地,下次请求时用户携带cookie进行请求,cookie解决用户身份问题,但是cookie不安全

cookie参数

  • name:规定 cookie 的名称
  • value:规定cookie的值
  • max_age:寿命,单位为秒,默认为None
  • expires:过期时间,和寿命是冲突的,默认值为None
  • path:cookie起作用的路径,默认为’/’
  • domain:cookie起作用的域名,默认值为None
  • secure:如果值为True用https协议传输cookie,默认值为False
  • httponly:如果值为Ture只用http协议传输,通常情况下js也可以拿到cookie,但是配置httponly为True,就http可以拿到,默认值为False

一个简单的cookie
我们在用户登录的时候向用户下发cookie,我们在这里用用户的email作为下发的cookie

def login(request):
    if request.method == "POST" and request.POST:
        name = request.POST.get("name")
        password = request.POST.get("password")
        user = User_one.objects.filter(userName=name)
        if user:
            if user[0].password == getPassword(password):
                response = HttpResponseRedirect("/student/page_student_list/1/")
                response.set_cookie("email", user[0].email)
                return response
            else:
                key = "密码错误"
        else:
            key = "用户名不存在"
    return render(request,"login.html", locals())

在这里插入图片描述这样在用户登录的时候我们就给他下发了一个cookie

当用户视图访问详情页的时候我们就验证他有没有这个cookie,如果有我们允许他访问,如果没有就让他跳转到登录界面
代码如下

def studentList(request):
    student_list = Student.objects.all()
    cookie = request.COOKIES
    email = cookie.get("email")
    if email:
        return render_to_response("tables.html", locals())
    else:
        return HttpResponseRedirect("/login/")

但是这样也有一个问题,就是如果我们有好多个页面都需要验证cookie才能访问,我们就得把验证cookie这一部分重复写很多遍,所以我们可以使用Python中的装饰器来解决这个问题,在需要的时候用这个装饰器装饰就可以了。
装饰器如下

def loginValid(fun):
    def inner(request, *args, **kwargs):
        cookie = request.COOKIES
        email = cookie.get("email")
        if email:
            return fun(request, *args, **kwargs)
        else:
            return HttpResponseRedirect("/login/")
    return inner

使用一下

@loginValid
def studentList(request):
    student_list = Student.objects.all()
    return render_to_response("tables.html", locals())

注意:我们这里使用用户的邮箱作为cookie进行验证,因为邮箱中没有汉字,不要用汉字作为cookie,会出问题的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值