Home  >  Article  >  Backend Development  >  Analyze the usage of cookies in Django

Analyze the usage of cookies in Django

巴扎黑
巴扎黑Original
2017-08-18 11:07:271419browse

Cookie is a record left by the browser on the client. This record can be kept in memory or on the hard disk. In Django, reading and setting cookies is very simple. Next, I will share with you the use of cookies in Django through this article. Friends who are interested should take a look.

Cookie is a record left by the browser on the client. This record can be kept in memory or on the hard disk. . Because HTTP requests are stateless, the server or client can maintain state in the session by reading cookie records. For example, a common application scenario is the login status. In Django, reading and setting cookies is very simple. The format of the cookie itself is similar to a dictionary, so it can be obtained through the key or get of the request; then its setting is set through the set_cookie of the response object; if you want to cancel the cookie, just set the expiration time to the current time.

Get Cookie:


request.COOKIES['key']
request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
  参数:
    default: 默认值
    salt: 加密盐
    max_age: 后台控制过期时间

Set 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获取(不是绝对,底层抓包可以获取到也可以被覆盖)

Example 1 Set up a login login interface, a jump interface after successful index login. If you are not logged in, it will automatically jump to the login interface

views.py


def index(reqeust):
  # 获取当前已经登录的用户
  v = reqeust.COOKIES.get('username111')
  if not v:
    return redirect('/login/')
  return render(reqeust,'index.html',{'current_user': v})

Note that there are two methods for cookie timeout, one is to directly specify max_age (timeout after N seconds), the other is to specify expires followed by a specific time object

httponly can JavaScript is prohibited from obtaining this value, but it is actually of no use. Chrome or packet capture can easily obtain all cookies

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>

Example 2:

In real life, the function of this verification cookie is usually written as a decorator, so that it is directly above other functions Just call it

Change Example 1


def auth(func):
  def inner(reqeust,*args,**kwargs):
    v = reqeust.COOKIES.get(&#39;username111&#39;)
    if not v:
      return redirect(&#39;/login/&#39;)
    return func(reqeust, *args,**kwargs)
  return inner
@auth
def index(reqeust):
  # 获取当前已经登录的用户
  v = reqeust.COOKIES.get(&#39;username111&#39;)
  return render(reqeust,&#39;index.html&#39;,{&#39;current_user&#39;: v})

Example 3: We know that we can use fbv or cbv to route functions. Example 2 uses the fbv method, which can also be implemented using cbv.

In cbv, if you only plan to decorate one method, then just add @method_decorator directly in front of the method; if you plan to decorate all methods in this class, Then decorate the top of the entire class

views.py


@method_decorator(auth,name=&#39;dispatch&#39;)
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(&#39;username111&#39;)
    return render(reqeust,&#39;index.html&#39;,{&#39;current_user&#39;: v})
  def post(self,reqeust):
    v = reqeust.COOKIES.get(&#39;username111&#39;)
    return render(reqeust,&#39;index.html&#39;,{&#39;current_user&#39;: v})
urls.py
 url(r&#39;^order/&#39;, views.Order.as_view()),

Example 4 We can also set cookies through JavaScript or JQuery, such as in the front Based on the paging code, we add a function to customize the number of rows displayed.

user_list.html Here is a JQuery plug-in, which makes it easier to read and set cookies; moreover, we also limit the scope of cookie use, not the default all scopes, but only limited to /user_list In the path


<!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 &#39;li.html&#39; %}
    {% endfor %}
  </ul>
  <p>
    <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>
  </p>
  <p class="pagination">
    {{ page_str }}
  </p>
  <script src="/static/jquery-1.12.4.js"></script>
  <script src="/static/jquery.cookie.js"></script>
  <script>
    $(function(){
        var v = $.cookie(&#39;per_page_count&#39;, {&#39;path&#39;: "/user_list/`"});
        console.log(v)
        $(&#39;#ps&#39;).val(v);
    });
    function changePageSize(ths){
      var v = $(ths).val();
      console.log(v);
      $.cookie(&#39;per_page_count&#39;,v, {&#39;path&#39;: "/user_list/"});     
      location.reload();
    }
  </script>
</body>
</html>

views.py gets the number of rows per page from the front end and passes it to our paging class during instantiation


def user_list(request):
  current_page = request.GET.get(&#39;p&#39;, 1)
  current_page = int(current_page)
  val = request.COOKIES.get(&#39;per_page_count&#39;,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, &#39;user_list.html&#39;, {&#39;li&#39;: data,&#39;page_str&#39;: page_str})

The above is the detailed content of Analyze the usage of cookies in Django. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn