1. 程式人生 > >djjango cookie和session 的幾種常用需求使用方法

djjango cookie和session 的幾種常用需求使用方法

------https://www.cnblogs.com/liuqingzheng/articles/8990027.html

需求情形一:正常設定cookie

def test_cookie_login(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        pwd = request.POST.get('pwd')
        if name == 'wudi' and pwd == '123':
            obj = redirect('index
') obj.set_cookie('is_login',True) obj.set_cookie('name',name) return obj return render(request,'test.html') def index(request): print(request.COOKIES) is_login = request.COOKIES.get('is_login') if is_login: return render(request,'index.html
',{'name':name}) else: return redirect('/test_cookie_login')

需求情形二:設定cookie在裝飾器裡

def login_auth(func):
    def inner(request,*args,**kwargs):
        is_login = request.COOKIES.get('is_login')
        if is_login:
            return func(request,*args,**kwargs)
        else:
            
return redirect('/test_cookie_login/') return inner @login_auth def index(request): name = request.COOKIES.get('name') return render(request,'index.html',{'name':name}) def test_cookie_login(request): if request.method == 'POST': name = request.POST.get('name') pwd = request.POST.get('pwd') if name == 'wudi' and pwd == '123': obj = redirect('index') obj.set_cookie('is_login',True) obj.set_cookie('name',name) return obj return render(request,'test.html')

需求情形三:為了使得已經鍵入登入index.html但卻未登入,登入成功之後直接跳轉到index.html,設定cookie里加入URL

def login_auth(func):
    def inner(request,*args,**kwargs):
        is_login = request.COOKIES.get('is_login')
        #為了使得已經鍵入登入index.html但卻未登入,登入成功之後直接跳轉到index.html
        next_url = request.get_full_path()
        if is_login:
            return func(request,*args,**kwargs)
        else:
            return redirect('/test_cookie_login/?next=%s'%next_url)
    return inner

@login_auth
def index(request):
    name = request.COOKIES.get('name')
    return render(request,'index.html',{'name':name})

def test_cookie_login(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        pwd = request.POST.get('pwd')
        # 為了使得已經鍵入登入index.html但卻未登入,登入成功之後直接跳轉到index.html
        url = request.GET.get('next')
        if name == 'wudi' and pwd == '123':
            obj = redirect(url)
            obj.set_cookie('is_login',True)
            obj.set_cookie('name',name)
            return obj
    return render(request,'test.html')