码迷,mamicode.com
首页 > 其他好文 > 详细

191107Django的Cookie和Session

时间:2019-11-22 01:21:04      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:cookie   user   设置   ESS   ret   max   htm   int   redirect   

  • 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

标签:cookie   user   设置   ESS   ret   max   htm   int   redirect   

原文地址:https://www.cnblogs.com/L-dongf/p/11909341.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!