目录
使用
def index(request):
# 读cookie
# is_login = request.COOKIES.get("is_login")
is_login = request.get_signed_cookie("is_login",salt="12*$543543534534554")
if is_login == "true":
user_id = request.get_signed_cookie("user_id",salt="12*$543543534534554") # salt 和设置cookie的时候一致
username = User.objects.get(pk=user_id).user
return render(request,"index.html",{"user":username})
else:
return redirect("/login/")
def login(request):
if request.method == "GET":
return render(request,"login.html")
else:
user = request.POST.get("user")
pwd = request.POST.get("pwd")
try:
user = User.objects.get(user=user, pwd=pwd)
res = redirect("/index/") # redirect 也是一个返回对象
# res.set_cookie("is_login","true",max_age=10000) # 只要是返回对象HttpResponse等 都可以设置cookie
# res.set_cookie("user_id", user.pk,max_age=10000) # 普通使用cookie 不带加密 可以在浏览器串改数据 max_age有效时长
res.set_signed_cookie("is_login","true",salt="12*$543543534534554")
res.set_signed_cookie("user_id", user.pk,salt="12*$543543534534554") # 设置加密cookie,设置一个yan salt指随便设置 设置之后在取的也要加上salt
return res
except Exception as e:
return redirect("/login/")
标签:get,request,cookie,user,使用,login,salt
From: https://www.cnblogs.com/py-zhq/p/16990582.html