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 at it. I hope it can help everyone.
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 ways to set the 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>
<!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>
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): # 获取当前已经登录的用户 v = reqeust.COOKIES.get('username111') return render(reqeust,'index.html',{'current_user': v})
@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()),
<!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> <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('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>
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})
How to set session expiration time using Django
##Examples of Django database addition, deletion, modification and query operationsCompare cookie and session instance operations in DjangoThe above is the detailed content of How to use cookies correctly in Django. For more information, please follow other related articles on the PHP Chinese website!