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

django cookies与session

时间:2018-11-16 13:58:33      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:get   pre   djang   date   one   print   als   render   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

django cookies与session

标签:get   pre   djang   date   one   print   als   render   session   

原文地址:https://www.cnblogs.com/tsgxj/p/9968847.html

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