django commonly used Web programs
Session mechanism
When a user visits the website for the first time, the server of the website will automatically create a Session object, which is equivalent to an identity certificate of the user in the website, and the Session can store the user's data information. When users jump between web pages, the data stored in the Session object will not be lost. Only when the Session expires or is cleaned up, the server will empty the data stored in the Session and terminate the Session
When obtaining the Session data of a user, first obtain the sessionid from the Cookie passed by the user, and then find the corresponding Session in the website server according to the sessionid.
The Session is stored in the memory of the server, so the data stored in the Session cannot be too large.
The Session of each user is received and scheduled through the MIDDLEWARE midview of Django
django.contrib.sessions.middleware.SessionMiddleware
When visiting the website, all HTTP requests are processed by the middleware, session middleware
It is equivalent to the HTTP request receiver, which makes corresponding scheduling according to the request information, and the execution of the program is determined by the configuration property installed of settings.py_ django.contrib.sessions in apps
Done.
django.contrib.sessions implements Session creation and operation processing, such as creating or storing user Session objects, managing Session life cycle, etc. it uses the database to store Session information by default, and the database name is django_session
Change the storage mode of Session
Session is stored in the database by default. If it is changed, the configuration information session can be added in settings.py_ Engine, which can specify the saving method of session.
django provides five ways to save sessions
# The database storage mode is django by default and does not need to be set in settings.py SESSION_ENGINE = 'django.contrib.sessions.backends.db' # Save as file SESSION_ENGINE = 'django.contrib.sessions.backends.file' # Use text save to set the file save path, which has relative path and absolute path SESSION_FILE_PATH = '/MyDjango' # /MyDjango represents that the text is saved in the root directory of the project MyDjango # Save as cache SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # Set the cache name. The default is the memory cache mode. The settings here are related to the settings of the cache mechanism SESSION_CACHE_ALIAS = 'default' # Save as database + cache SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' # Save as Cookie SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
Set Cookie related information in the browser
It is also set through the Session on the back end of the server
For example, the life cycle, transmission mode or save path of cookies
await a vacancy or job opening
Read / write operation of Session
The data type of Session can be understood as the dictionary type of Python. It is mainly read and written in the view function and obtained from the user request (request from the view function)
await a vacancy or job opening
Using session to realize rush purchase of goods (key)
His session storage realizes the data transmission of two page events, which I don't know
Notes to be filled
Caching mechanism
When the website access is too large, the response speed of the website must be greatly reduced, and the knowledge and can use the caching mechanism on the website.
Caching is to save the response content of a request to memory, database, file or cache system (Memcache). If an event receives the same request again, it will no longer execute the response process of the request, but directly obtain the response content of the request from memory or cache system and return it to the user.
Cache mode and configuration
django provides five different caching methods
await a vacancy or job opening
Each caching method needs to be determined according to the actual situation of the website. If the caching mechanism is used in the project, first set the relevant configuration of the cache in the configuration file settings.py
# Configuration of each cache mode
The cache configuration parameters BACKEND and LOCATION are required. Other configuration parameters can be selected by yourself.
Complete database cache configuration
CACHES = { # Default cache data table 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_cache_table', # TIMEOUT sets the lifetime of the cache in seconds. If None, it will never expire 'TIMEOUT': 60, 'OPTIONS': { # MAX_ENTRIES represents the maximum number of cached records 'MAX_ENTRIES': 1000, # When the maximum number of caches is reached, set the number of culled caches 'CULL_FREQUENCY': 3, } }, # Set up multiple cached data tables 'MyDjango': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'MyDjango_cache_table', } }
DJango allows you to configure and use many different types of caching methods at the same time. The configuration method is similar to that of multiple DATABASES. The creation of cache data tables depends on DATABASES in database configuration settings.py. If there are multiple DATABASES, they are generated in the database of default in DATABASES by default.
Use of cache
There are four ways to use cache, which are mainly divided according to different applicable objects.
Site wide cache View cache Route cache Template cache
The whole site cache is configured in the middleware of django,
MIDDLEWARE = [ # Configure site wide cache 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # Use Chinese 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # Configure site wide cache 'django.middleware.cache.FetchFromCacheMiddleware', ] # Sets the lifecycle of the cache CACHE_MIDDLEWARE_SECONDS = 15 # Set the cache data to be saved in the data table_ cache_ In table # The attribute value default comes from the default attribute of cache configuration CACHES CACHE_MIDDLEWARE_ALIAS = 'default' # Set cache path # Set cache table field cache_ Value of key # Used for shared caching between multiple sites of the same Django project CACHE_MIDDLEWARE_KEY_PREFIX = 'MyDjango' # Specify the name of a site
View cache
The cached data is generated during the execution of the view function or view class. The view is generated using the decorator and the cached data is saved.
The decorator has parameters timeout, cache and key_ Prefix, timeout is a required parameter, and the other two parameters are optional. The parameter has the same effect as the configuration attribute of the global cache
from django.shortcuts import render # Import cache_page from django.views.decorators.cache import cache_page # Parameter cache and configuration attribute cache_ MIDDLEWARE_ Same as alias # Parameter key_prefix and configuration attribute cache_ MIDDLEWARE_ KEY_ Same as prefix # Parameter timeout and configuration attribute cache_ MIDDLEWARE_ Same as seconds # CACHE_MIDDLEWARE_SECONDS takes precedence over the timeout parameter @cache_page(timeout=10, cache='MyDjango', key_prefix='MyView') def index(request): return render(request, 'index.html')
Route cache
Generated and saved in the route file urls.py, and the route cache also uses the cache function cache_page implementation.
from django.views.decorators.cache import cache_page urlpatterns = [ # Set routing cache on the homepage of the website path('', cache_page(timeout=10, cache='MyDjango', key_prefix='MyURL')(views.index), name='index'), # path('', views.index, name='index'), ]
Template cache
The template cache is realized through Django's cache tag. The cache tag can set the cache life cycle, cache keywords and cache data table (the parameters timeout, key_prefix and cache of the function cache_page). The setting order and code format of the three are fixed.
<div> {# Set template cache #} {% load cache %} {# 10 Represents the life cycle #} {# MyTemp Represents the of cached data cache_key field #} {# using="MyDjango"Represents a cached data table #} {% cache 10 MyTemp using="MyDjango" %} <div>Hello Django</div> {# End of cache #} {% endcache %} </div>
CSRF protection
CSRF protection is only applicable to POST requests and does not protect GET requests, because GET requests access website resources in a read-only form and generally do not destroy and tamper with network data.
Protection is to generate a hidden control using template syntax {% csrf_token%}
<input type="hidden" name="csrfmiddlewaretoken" value="zUJfhT41OyX80zCqbbytV4Lc5hoQgATmg5wTeh4XnpnBrbaSytkvw0WUcNC0Dtfd">
The attribute value value of the hidden control is randomly generated by Django. When the user submits the form, Django will verify whether the csrfmiddlewaretoken of the form is consistent with the csrfmiddlewardtoken saved by itself. Each time the user submits the form, the attribute value of the hidden control will change accordingly.
Cancel CSRF protection
Delete the {% csrf_token%} of the template file, and add the decorator @ CSRF in the corresponding view function_ exempt
from django.views.decorators.csrf import csrf_protect from django.views.decorators.csrf import csrf_exempt # Add CSRF protection # @csrf_protect # Cancel CSRF protection @csrf_exempt def index(request): return render(request, 'index.html')
If no decorator is added to the corresponding view function @csrf_exempt
, when the user submits the form, the program will throw a 403 exception page due to CSRF verification failure.
If you want to completely cancel the CSRF protection of the whole website, you can comment out midview in settings.py
django.middleware.csrf.CsrfViewMiddleware
However, if you want to set CSRF protection on some requests, {% csrf_token%} is added to the corresponding html file, and the decorator @ CSRF is added to the corresponding view function_ protect
@csrf_protect def index(request): return render(request, 'index.html')
If the front-end AJAX is used to submit the form data to Django when the web form is sent, Django has set the CSRF protection function. When Ajax sends a POST request, the request parameter csrfiddlewaretoken must be set, otherwise Django will treat the current request as a malicious request. The function code of Ajax sending POST request is as follows
await a vacancy or job opening(Very important)
Message frame
In web applications, when users complete a function operation, the website will have corresponding message prompts. Django's built-in message framework can be directly called by developers. It allows developers to set function engine, message type and message class content.
The message framework consists of middleware SessionMiddleware, MessageMiddleware and installed_ Django.contrib.sessions and django.contrib.messages in apps are implemented together.
Concrete implementation
The function engine of MessageMiddleware uses FallbackStorage by default, and FallbackStorage is implemented on the basis of session, so the SessionMiddleware middleware must be set in front of MessageMiddleware.
Relevant information It's a little different
Source location of MessageMiddleware
await a vacancy or job opening
MessageMiddleware source file contains files and functions
await a vacancy or job opening
Use of message framework
Message framework is mainly used in views and templates, and message framework is used in different ways in view functions and view classes
Set the function engine of the message frame
# MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage' # MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' # FallbackStorage is used by default and does not need to be set MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
Set url
await a vacancy or job opening
Define the corresponding view function
Here is a context handler, which is worth noting
await a vacancy or job opening
Paging function
Factors to consider for paging function:
1. Whether there are upper (lower) pages in the number of pages accessed by the current user
2. Whether the number of pages accessed exceeds the maximum number of pages
3. How to intercept data by page and how to set the amount of data per page
Paginator class, which mainly implements paging, defines 4 initialization parameters and 8 class methods. The description of each initialization parameter and class method is as follows
await a vacancy or job opening
After we instantiate Paginator, we call get from the instantiated object_ Page() to get the instantiated object of the page class. You can find the definition process of the page class in the source file paginator.py. It defines three initialization parameters and seven class methods
await a vacancy or job opening
Using the shell mode of django, briefly describe the use of paging function
In [1]: # Import paging function module In [2]: from django.core.paginator import Paginator In [3]: # Generate data list In [4]: objects = [chr(x) for x in range(97,107)] In [5]: objects Out[5]: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] In [6]: # Paginate the data list every 3 elements In [7]: p = Paginator(objects,3) In [8]: # Output all data, that is, the whole data list In [9]: p.object_list Out[9]: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] In [10]: # Get data list length In [11]: p.count Out[11]: 10 In [12]: Total pages after Pagination --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-12-b9a482fe307d> in <module> ----> 1 Total pages after Pagination NameError: name 'Total pages after Pagination' is not defined In [13]: # Total pages after Pagination In [14]: p.num_pages Out[14]: 4 In [15]: # Convert the number of pages to a range loop object In [16]: p.page_range Out[16]: range(1, 5) In [17]: # Get the data information of the second page In [18]: page2 = p.get_page(2) In [19]: # Determine whether there is a previous page on the second page In [20]: page2.has_previous() Out[20]: True In [21]: # Determine whether the next page exists on the second page In [22]: page2.has_next() Out[22]: True In [23]: # If the current page has a next page, the number of pages of the next page is output In [24]: # Otherwise, an EmptyPage exception is thrown In [25]: page2.next_page_number() Out[25]: 3 In [26]: # If the current page has a previous page, the number of pages of the previous page is output In [27]: # Otherwise, an EmptyPage exception is thrown In [28]: page2.previous_page_number() Out[28]: 1 In [29]: # Judge whether the current page has a previous page or a next page In [30]: page2.has_other_pages() Out[30]: True In [31]: # Output the data content corresponding to the second page In [32]: page2.has_other_pages() Out[32]: True In [33]: page2.object_list Out[33]: ['d', 'e', 'f'] In [34]: # Output the position of the first row of data on the second page in the whole data list In [35]: # The data position is calculated from 1 In [36]: page2.start_index() Out[36]: 4 In [37]: # Output the position of the last row of data on the second page in the whole data list In [38]: # The data position is calculated from 1 In [39]: page2.end_index() Out[39]: 6
The specific use of the dingo paging function is mainly used in the view function in views.py. Generally, you need to pass custom parameters into the view function to instantiate a page variable and act on the template file
await a vacancy or job opening