191107Django的Cookie和Session
Posted l-dongf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了191107Django的Cookie和Session相关的知识,希望对你有一定的参考价值。
- Cookie的使用
from django.shortcuts import render,redirect
def login(request):
print("1",request.COOKIES)
if request.method == "POST":
name = request.POST.get("user")
pwd = request.POST.get("pwd")
if name == "dongfei" and pwd == "dongfei":
ret = redirect("/index")
ret.set_cookie("id",'14bae99719abcf1f89f5',max_age=10) #设置cookie的超时时间
return ret
return render(request,"login.html",locals())
def index(request):
if request.COOKIES.get("id",None) == '14bae99719abcf1f89f5':
name = "dongfei"
return render(request,"index.html",locals())
else:
return redirect("/login/")
- Cookie和Session的使用
from django.shortcuts import render,redirect
def login(request):
print("COOKIES",request.COOKIES)
print("SESSION",request.session)
if request.method == "POST":
name = request.POST.get("user")
pwd = request.POST.get("pwd")
if name == "dongfei" and pwd == "dongfei":
# ret = redirect("/index")
# ret.set_cookie("id",'14bae99719abcf1f89f5',max_age=10) #设置cookie的超时时间
# return ret
request.session["is_login"] = True #设置session,需要migrate数据库
request.session["user"] = name
# del request.session["user"] #删除session
# request.session.set_expiry(10) #设置session超时时间
return redirect("/index/")
return render(request,"login.html",locals())
def index(request):
# if request.COOKIES.get("id",None) == '14bae99719abcf1f89f5':
# name = "dongfei"
# return render(request,"index.html",locals())
if request.session.get("is_login",None):
name = request.session.get("user")
return render(request,"index.html",locals())
else:
return redirect("/login/")
以上是关于191107Django的Cookie和Session的主要内容,如果未能解决你的问题,请参考以下文章