溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Django中cookie的使用案例

發(fā)布時間:2021-05-08 09:53:41 來源:億速云 閱讀:105 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)Django中cookie的使用案例的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

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

獲取Cookie:

request.COOKIES['key']
request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
  參數(shù):
    default: 默認(rèn)值
    salt: 加密鹽
    max_age: 后臺控制過期時間

設(shè)置Cookie:

rep = HttpResponse(...) 或 rep = render(request, ...)
rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt='加密鹽',...)
  參數(shù):
    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協(xié)議傳輸,無法被JavaScript獲?。ú皇墙^對,底層抓包可以獲取到也可以被覆蓋)

例1  設(shè)置一個login登錄界面,一個index登錄成功之后的跳轉(zhuǎn)界面,如果沒有登錄那么自動跳轉(zhuǎn)到登錄界面

views.py

def index(reqeust):
  # 獲取當(dāng)前已經(jīng)登錄的用戶
  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>
  <h2>歡迎登錄:{{ current_user }}</h2>
</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:

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

把例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):
  # 獲取當(dāng)前已經(jīng)登錄的用戶
  v = reqeust.COOKIES.get('username111')
  return render(reqeust,'index.html',{'current_user': v})

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

cbv里面,如果只打算裝飾一個方法,那么直接在方法前面加個@method_decorator就行;如果打算裝飾這個類里面所有的方法,那么在整個類的最上面進(jìn)行裝飾

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來設(shè)置Cookie,比如在前面分頁的代碼基礎(chǔ)上,我們增加一個自定義顯示行數(shù)的功能。

user_list.html  這里下了一個JQuery的插件,這樣讀取設(shè)置cookie比較容易;而且,我們還限制了cookie的使用范圍,不是默認(rèn)的所有范圍,而是僅僅局限于/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  從前端獲取每頁行數(shù),實例化的時候傳遞給我們的分頁類

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})

感謝各位的閱讀!關(guān)于“Django中cookie的使用案例”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI