Django緩存使用方法

Django緩存分爲Session和Cookie:Session爲放在服務器端的緩存;Cookie爲放在客戶端(瀏覽器)的緩存。html

Session通常用來保存登陸會話;Cookie通常用來保存一些個性化的設置。python

Session示例:web

#!/usr/bin/env python
#-*- encoding:utf-8 -*-

from django.shortcuts import render,redirect


# Create your views here.

def login(request):

    if request.method == 'POST':
        user = request.POST.get('username',None)
        pwd = request.POST.get('password',None)

        if user == 'alex' and pwd == '123':   #登陸成功
            request.session['is_login'] = {'user':user}    #設置session,表示用戶登陸成功
            return redirect('/login/index/')
        else:  #登陸失敗
            return render(request,'login/login.html',{'msg':'用戶名或密碼錯誤'})

    return render(request,'login/login.html')

def index(request):

    user_dict = request.session.get('is_login',None)   #獲取session,用於判斷用戶是否登陸成功
    if  user_dict:
        return render(request, 'login/index.html',{'username':user_dict['user']})
    else:
        return redirect('/login/login')


def logout(request):
    del request.session['is_login']   #刪除session

    return redirect('/login/login')

 

Cookie示例:django

def Page(request,page):
    #第二種分頁方式
    counts = Host.objects.all().count()  # 獲取數據總條數

    #print request.POST

    per_item = request.COOKIES.get('pager_num',5)  #從cookie中獲取key爲pager_num的值,獲取不到則設置默認值爲5
    per_item = int(per_item)
    #print 'per_item:',per_item

    pages = PageInfo(page,counts,'/web/page/',per_item)
    result = Host.objects.all()[pages.start_page:pages.end_page]  # 獲取第page頁內容
    page_string = pages.page_string
    #print 'page_string:',page_string

    ctx = {
        'data':result,
        'count':counts,
        'page_string':page_string,
    }

    response = render(request,'page.html',ctx)
    #response.set_cookie(key='k1',value='v1')  #設置cookie
    #request.COOKIES    #獲取cookie
    return response
相關文章
相關標籤/搜索