django cookies与session

1. cookiies 
# cookies
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 =='bob' and pwd =='123':
            ret = redirect('/APP02/home/')
            ret.set_cookie('username',{'name':""},max_age=30*3600,expires=datetime.datetime.utcnow()+datetime.timedelta(minutes=30))
            # 设置cookies有限时间为10秒
            return ret
    return render(request,'login.html',locals())

def home(request):

    if request.COOKIES.get('username',None):
        return render(request,'home.html',locals())
    else:
        return redirect('/APP02/login/')

  2. session +cookies 

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 =='bob' and pwd =='123':
            request.session.set_expiry(30*3600)
            # 设置session有效时间
            request.session['is_login'] = True
            request.session['user'] = name
            return redirect('/APP02/home/')
    return render(request,'login.html',locals())

def home(request):

    if request.session.get('is_login',False):
        user = request.session.get('user',None)
        return render(request,'home.html',locals())
    else:
        return redirect('/APP02/login/')

  

 

参考链接:

https://www.07net01.com/2016/03/1364624.html

posted @ 2018-11-16 13:35  起个名字真难1  阅读(190)  评论(0编辑  收藏  举报