Cookie usage in Django and djangocookie

Source: Internet
Author: User

Cookie usage in Django and djangocookie

Cookie is a record left by the browser on the client. This record can be retained on the memory or hard disk. Because Http requests are stateless, the server or client can maintain the session status by reading the cookie record. For example, a common application scenario is logon status. In Django, it is easy to read and set cookies. The Cookie format is similar to a dictionary. Therefore, you can obtain the cookie through the request key or get. Then, the Cookie is set through the set_cookie of the response object. If you want to cancel the cookie, 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) parameter: default salt: Encrypted salt max_age: the backend controls the expiration time

Set Cookie:

Rep = HttpResponse (...) or rep = render (request ,...) rep. set_cookie (key, value ,...) rep. set_signed_cookie (key, value, salt = 'encrypted sale ',...) parameter: key, key value = '', value max_age = None, timeout expires = None, timeout (IE requires expires, so set it if hasn't been already .) path = '/', the path in which the Cookie takes effect,/indicates the root path. Special: the cookie with the path can be accessed by any url page. domain = None, the domain name for which the Cookie takes effect is secure = False. https transmission httponly = False can only be transmitted over http and cannot be obtained by JavaScript (not absolute, the underlying packet capture can be obtained or overwritten)

Example 1: Set a login logon interface and a jump interface after index logon is successful. If you are not logged on, the logon interface is automatically displayed.

Views. py

Def index (reqeust): # obtain 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 two Cookie timeout Methods: one is to directly specify max_age (timeout after N seconds), and the other is to specify a specific time object after expires

Httponly can prohibit JavaScript from getting this value, but in fact there is no such thing, chrome or packet capture can easily get all cookies

Index.html

<! DOCTYPE html> 

Login.html

<! DOCTYPE html> 

Example 2:

In real life, the function of cookie verification is generally written as a decorator, so that it can be called directly on other functions.

Change 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 ): # obtain the currently logged-on user v = reqeust. COOKIES. get ('username111') return render(reqeust,'index.html ', {'current _ user': v })

Example 3: fbv or cbv can be used to route functions. Example 2 uses the fbv method, and cbv can also be used.

In cbv, if only one method is to be decorated, simply add @ method_decorator in front of the method. If you want to decorate all the methods in this class, in this case, decoration is performed on 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: You can also set the Cookie through JavaScript or JQuery. For example, you can add a function to customize the number of lines displayed based on the Code on the previous page.

User_list.html has a JQuery plug-in, which makes it easier to read and set cookies. In addition, we also limit the use range of cookies, not all the default ranges, it is limited to the path/user_list.

<!DOCTYPE html>

Views. py gets the number of lines per page from the front end. The paging class passed to us during instantiation

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

Summary

The above section describes how to use cookies in Django. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.