Home Backend Development PHP Tutorial Analyze the usage of cookies in Django

Analyze the usage of cookies in Django

Aug 18, 2017 am 11:07 AM
cookie django ie

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: 后台控制过期时间
Copy after login

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

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})
Copy after login

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>
Copy after login

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>
Copy after login

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})
Copy after login

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()),
Copy after login

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>
Copy after login

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})
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Django vs. Flask: A comparative analysis of Python web frameworks Django vs. Flask: A comparative analysis of Python web frameworks Jan 19, 2024 am 08:36 AM

Django and Flask are both leaders in Python Web frameworks, and they both have their own advantages and applicable scenarios. This article will conduct a comparative analysis of these two frameworks and provide specific code examples. Development Introduction Django is a full-featured Web framework, its main purpose is to quickly develop complex Web applications. Django provides many built-in functions, such as ORM (Object Relational Mapping), forms, authentication, management backend, etc. These features allow Django to handle large

Django Framework Pros and Cons: Everything You Need to Know Django Framework Pros and Cons: Everything You Need to Know Jan 19, 2024 am 09:09 AM

Django is a complete development framework that covers all aspects of the web development life cycle. Currently, this framework is one of the most popular web frameworks worldwide. If you plan to use Django to build your own web applications, then you need to understand the advantages and disadvantages of the Django framework. Here's everything you need to know, including specific code examples. Django advantages: 1. Rapid development-Djang can quickly develop web applications. It provides a rich library and internal

How to upgrade Django version: steps and considerations How to upgrade Django version: steps and considerations Jan 19, 2024 am 10:16 AM

How to upgrade Django version: steps and considerations, specific code examples required Introduction: Django is a powerful Python Web framework that is continuously updated and upgraded to provide better performance and more features. However, for developers using older versions of Django, upgrading Django may face some challenges. This article will introduce the steps and precautions on how to upgrade the Django version, and provide specific code examples. 1. Back up project files before upgrading Djan

What should I do if win11 cannot use ie11 browser? (win11 cannot use IE browser) What should I do if win11 cannot use ie11 browser? (win11 cannot use IE browser) Feb 10, 2024 am 10:30 AM

More and more users are starting to upgrade the win11 system. Since each user has different usage habits, many users are still using the ie11 browser. So what should I do if the win11 system cannot use the ie browser? Does windows11 still support ie11? Let’s take a look at the solution. Solution to the problem that win11 cannot use the ie11 browser 1. First, right-click the start menu and select "Command Prompt (Administrator)" to open it. 2. After opening, directly enter "Netshwinsockreset" and press Enter to confirm. 3. After confirmation, enter "netshadvfirewallreset&rdqu

Detailed explanation of where browser cookies are stored Detailed explanation of where browser cookies are stored Jan 19, 2024 am 09:15 AM

With the popularity of the Internet, we use browsers to surf the Internet have become a way of life. In the daily use of browsers, we often encounter situations where we need to enter account passwords, such as online shopping, social networking, emails, etc. This information needs to be recorded by the browser so that it does not need to be entered again the next time you visit. This is when cookies come in handy. What are cookies? Cookie refers to a small data file sent by the server to the user's browser and stored locally. It contains user behavior of some websites.

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

How to use the Django framework to create a project in PyCharm How to use the Django framework to create a project in PyCharm Feb 19, 2024 am 08:56 AM

Tips on how to create projects using the Django framework in PyCharm, requiring specific code examples. Django is a powerful Python Web framework that provides a series of tools and functions for quickly developing Web applications. PyCharm is an integrated development environment (IDE) developed in Python, which provides a series of convenient functions and tools to increase development efficiency. Combining Django and PyCharm makes it faster and more convenient to create projects

Django: A magical framework that can handle both front-end and back-end development! Django: A magical framework that can handle both front-end and back-end development! Jan 19, 2024 am 08:52 AM

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

See all articles