COOKIE和SEESION的配合使用
Posted 425500828zjy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了COOKIE和SEESION的配合使用相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="post"> <p>姓名<input type="text" name="user"></p> <p>密码<input type="password" name="pwd"></p> <input type="submit"> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>{{ name }}</h1> </body> </html>
from django.shortcuts import render,redirect # Create your views here. def login(request): print("COOKIES",request.COOKIES) print("SESSION",request.session) if request.method == "POST": #请求方式post name = request.POST.get("user") pwd = request.POST.get("pwd") if name == "yuan" and pwd == "123": # ret = redirect("/index/") # ret.set_cookie("username",{""}) # return ret request.session["is_login"] = True request.session["user"] = name #为session添加字典数据,作为index函数里的判断依据 return redirect("/index/") return render(request,"login.html") def index(request): # if request.COOKIES.get("username",None): # name = request.COOKIES.get("username",None) # return render(request,"index.html",locals()) #判断session字典中key为"is_login"是否存在,不存在返回/login/页面 if request.session.get("is_login",None): name = request.session.get("user",None) return render(request,"index.html",locals()) else: return redirect("/login/")
以上是关于COOKIE和SEESION的配合使用的主要内容,如果未能解决你的问题,请参考以下文章