1. 程式人生 > >Django 中 cookie的使用

Django 中 cookie的使用

django cookie

Cookie是瀏覽器在客戶端留下的一段記錄,這段記錄可以保留在內存或者硬盤上。因為Http請求是無狀態的,通過讀取cookie的記錄,服務器或者客戶端可以維持會話中的狀態。比如一個常見的應用場景就是登錄狀態。Django裏面,對cookie的讀取和設置很簡單。Cookie本身的格式類似字典,因此可以通過request的key或者get獲取;然後他的設置則是通過response對象的set_cookie設定; 如果要取消cookie,把過期時間設置為當前時間就行了。


獲取Cookie:

request.COOKIES[‘key‘]
request.get_signed_cookie(key, default=RAISE_ERROR, salt=‘‘, max_age=None)
    參數:
        default: 默認值
        salt: 加密鹽
        max_age: 後臺控制過期時間


設置Cookie:

rep = HttpResponse(...) 或 rep = render(request, ...)
 
rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt=‘加密鹽‘,...)
    參數:
        key,              鍵
        value=‘‘,         值
        max_age=None,     超時時間
        expires=None,     超時時間(IE requires expires, so set it if hasn‘t been already.)
        path=‘/‘,         Cookie生效的路徑,/ 表示根路徑,特殊的:跟路徑的cookie可以被任何url的頁面訪問
        domain=None,      Cookie生效的域名
        secure=False,     https傳輸
        httponly=False    只能http協議傳輸,無法被JavaScript獲取(不是絕對,底層抓包可以獲取到也可以被覆蓋)



例1 設置一個login登錄界面,一個index登錄成功之後的跳轉界面,如果沒有登錄那麽自動跳轉到登錄界面


views.py

def index(reqeust):
    # 獲取當前已經登錄的用戶
    v = reqeust.COOKIES.get(‘username111‘)
    if not v:
        return redirect(‘/login/‘)
    return render(reqeust,‘index.html‘,{‘current_user‘: v})

註意Cookie的超時時間有2種方式,一個是直接指定max_age(N秒後超時),一個是指定expires後面跟一個具體的時間對象

httponly可以禁止JavaScript獲取這個值,但是實際上沒有什麽鳥用,chrome或者抓包都能輕松獲取所有的cookie



index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>歡迎登錄:{{ current_user }}</h1>
</body>
</html>


login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form action="/login/" method="POST">
        <input type="text" name="username" placeholder="用戶名" />
        <input type="password" name="pwd" placeholder="密碼" />
        <input type="submit" />
    </form>
</body>
</html>


例2:

現實生活中,一般是把這個驗證cookie的功能寫成裝飾器,這樣直接在其他函數上面調用就行了

把例1改一下

def auth(func):
    def inner(reqeust,*args,**kwargs):
        v = reqeust.COOKIES.get(‘username111‘)
        if not v:
            return redirect(‘/login/‘)
        return func(reqeust, *args,**kwargs)
    return inner
    
@auth
def index(reqeust):
    # 獲取當前已經登錄的用戶
    v = reqeust.COOKIES.get(‘username111‘)
    return render(reqeust,‘index.html‘,{‘current_user‘: v})


例3: 我們知道可以使用fbv或者cbv來路由函數。例2使用了fbv的方式,用cbv也能實現

cbv裏面,如果只打算裝飾一個方法,[email protected]_decorator就行;如果打算裝飾這個類裏面所有的方法,那麽在整個類的最上面進行裝飾


views.py

@method_decorator(auth,name=‘dispatch‘)
class Order(views.View):
    # @method_decorator(auth)
    # def dispatch(self, request, *args, **kwargs):
    #     return super(Order,self).dispatch(request, *args, **kwargs)
    # @method_decorator(auth)
    def get(self,reqeust):
        v = reqeust.COOKIES.get(‘username111‘)
        return render(reqeust,‘index.html‘,{‘current_user‘: v})
    def post(self,reqeust):
        v = reqeust.COOKIES.get(‘username111‘)
        return render(reqeust,‘index.html‘,{‘current_user‘: v})


urls.py

  url(r‘^order/‘, views.Order.as_view()),


例4 我們還可以通過JavaScript或者JQuery來設置Cookie,比如在前面分頁的代碼基礎上,我們增加一個自定義顯示行數的功能。


user_list.html 這裏下了一個JQuery的插件,這樣讀取設置cookie比較容易;而且,我們還限制了cookie的使用範圍,不是默認的所有範圍,而是僅僅局限於/user_list這個路徑裏面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        .go{
            width:20px;
             border: solid 1px;
            color: #66512c;
            display: inline-block;
            padding: 5px;
        }
        .pagination .page{
            border: solid 1px;
            color: #66512c;
            display: inline-block;
            padding: 5px;
            background-color: papayawhip;
            margin: 5px;
        }
        .pagination .page.active{
            background-color: brown;
            color: white;
        }
    </style>
</head>
<body>
    <ul>
        {% for item in li %}
            {% include ‘li.html‘ %}
        {% endfor %}
    </ul>
    <div>
        <select id="ps" onchange="changePageSize(this)">
            <option value="10">10</option>
            <option value="30">30</option>
            <option value="50">50</option>
            <option value="100">100</option>
        </select>
    </div>
    <div class="pagination">
        {{ page_str }}
    </div>
    <script src="/static/jquery-1.12.4.js"></script>
    <script src="/static/jquery.cookie.js"></script>
    <script>
        $(function(){
                var v = $.cookie(‘per_page_count‘, {‘path‘: "/user_list/`"});
                console.log(v)
                $(‘#ps‘).val(v);
        });
        function changePageSize(ths){
            var v = $(ths).val();
            console.log(v);
            $.cookie(‘per_page_count‘,v, {‘path‘: "/user_list/"});          
            location.reload();
        }
    </script>
</body>
</html>



views.py 從前端獲取每頁行數,實例化的時候傳遞給我們的分頁類

def user_list(request):
    current_page = request.GET.get(‘p‘, 1)
    current_page = int(current_page)
    val = request.COOKIES.get(‘per_page_count‘,10)
    val = int(val)
    page_obj = pagination.Page(current_page,len(LIST),val)

    data = LIST[page_obj.start:page_obj.end]
    page_str = page_obj.page_str("/user_list/")
    return render(request, ‘user_list.html‘, {‘li‘: data,‘page_str‘: page_str})


技術分享

本文出自 “麻婆豆腐” 博客,請務必保留此出處http://beanxyz.blog.51cto.com/5570417/1956951

Django 中 cookie的使用