django cookies与session

Posted tsgxj

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于django cookies与session的主要内容,如果未能解决你的问题,请参考以下文章

Django框架——cookie与session简介django操作cookie与sessiondjango中间件

[Django高级之cookie与session]

浅析Django之session与cookie

django cookies与session

Django Cookies与Session组件

Django cookie与session