Django cookie
发布日期:2021-06-29 04:55:55 浏览次数:2 分类:技术文章

本文共 1965 字,大约阅读时间需要 6 分钟。

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

使用一下

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

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

转载地址:https://blog.csdn.net/Zhang_Chao_1998/article/details/86098292 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:用户登录逻辑
下一篇:form表单

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月20日 04时05分14秒