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 id="欢迎登录-nbsp-current-user-nbsp">欢迎登录:{{ 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 itChange 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 @auth def index(reqeust): # 获取当前已经登录的用户 v = reqeust.COOKIES.get('username111') return render(reqeust,'index.html',{'current_user': 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 classviews.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 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 '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>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('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})
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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools