How cookies are used correctly in Django

Source: Internet
Author: User
In Django, it's easy to read and set cookies. Next through this article to share the use of cookies in Django, interested friends to see together, hoping to help everyone.

A cookie is a record that a browser leaves on the client, which can be kept in memory or on a hard disk. Because the HTTP request is stateless, the server or client can maintain state in the session by reading the cookie's record. For example, a common application scenario is login status. In Django, it's easy to read and set cookies. The cookie itself is formatted like a dictionary, so it can be obtained via the request key or get, and his settings are set by the Set_cookie of the response object; If you want to cancel the cookie, set the expiration time to the current time.

To obtain a cookie:


Request. cookies[' key ']request.get_signed_cookie (key, Default=raise_error, salt= ', max_age=none)  parameters:    Default: Defaults    Salt: Encryption salt    max_age: Background control Expiration Time

Set Cookies:


Rep = HttpResponse (...) or rep = render (Request, ...) Rep.set_cookie (Key,value,...) Rep.set_signed_cookie (key,value,salt= ' crypto Salt ',...)  Parameters: Key    ,       key    value= ',     value    max_age=none,   timeout time    expires=none,   timeout (IE requires expires , so set it if hasn ' t been already.)    Path= '/',     cookie takes effect path,/indicates root path, Special: Cookie with path can be accessed by any URL of the page    Domain=none,   the cookie is in effect the domain name    secure= False,   HTTPS transport    Httponly=false can  only be transmitted by the HTTP protocol and cannot be obtained by JavaScript (not absolute, the underlying capture can be obtained or overwritten)

Example 1 set a login login interface, an index login successful after the jump interface, if not logged in then automatically jump to the login screen

views.py


def index (reqeust):  # Gets the currently logged-on user  v = reqeust. Cookies.get (' username111 ')  if not V:    return redirect ('/login/')  return render (Reqeust, ' index.html ', {' Current_User ': v})

Note that there are 2 ways to time out a cookie, one is to specify Max_age directly (timeout after n seconds), and one is to specify expires followed by a specific time object

HttpOnly can prohibit JavaScript from getting this value, but in fact there is no bird, chrome or grab bag can easily get all the cookies

Index.html


<! DOCTYPE html>

Login.html


<! DOCTYPE html>

Example 2:

In real life, the function of this authentication cookie is generally written as an adorner, so that it can be called directly on the other functions.

Change the example 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@authdef Index (reqeust):  # Gets the currently logged-on user  v = reqeust. Cookies.get (' username111 ')  return render (Reqeust, ' index.html ', {' Current_User ': v})

Example 3: We know we can use FBV or CBV to route the function. Example 2 using the Fbv method, with the CBV can also be achieved

CBV inside, if only intends to decorate a method, then directly in front of the method to add a @method_decorator on the line; If you intend to decorate all the methods in this class, then decorate the top of the entire class

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 ()),

Example 4 We can also use JavaScript or jquery to set cookies, such as the previous pagination of the code based on, we added a custom display line number of the function.

user_list.html here is a jquery plug-in, so it is easier to read settings cookies, and we also limit the use of cookies, not the default range, but only in the path of/user_list


<! DOCTYPE html>

Views.py gets the number of rows per page from the front end, which is passed to our paging class when instantiated


def user_list (Request):  current_page = Request. Get.get (' P ', 1)  current_page = Int (current_page)  val = Request. Cookies.get (' Per_page_count ', ten)  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})

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.