A context processor
Context processor can return some data, it can be used in the global template. For example, the user's login information, you need to use a lot of pages, then we can be placed in the context of the processor, there is no need to return the object in each view function.
In settings.TEMPLATES.OPTIONS.context_processors
the, has many built-context processor. The context processor acting as follows:
django.template.context_processors.debug
: Add adebug
andsql_queries
variable. In the template you can view some database query by him.django.template.context_processors.request
: Add arequest
variable. Thisrequest
variable is the first argument to the view function.django.contrib.auth.context_processors.auth
:Django
There are built-in user systems, this processor will add a contextuser
object.django.contrib.messages.context_processors.messages
: Add amessages
variable.django.template.context_processors.media
: It can be read in the templateMEDIA_URL
. For example, you want to use in the template file to upload, then you need to use this timesettings.py
setMEDIA_URL
to spliceurl
. Sample code is as follows:<img src="" />
django.template.context_processors.static
: You can use the templateSTATIC_URL
.django.template.context_processors.csrf
: You can use the templatecsrf_token
variables to generate acsrf token
.
Custom context processor:
Sometimes we want to return to their own data. So this time we can customize the context processor. Step custom context processor as follows:
- You can be the basis of this context processor belongs
app
, then thisapp
creates a document designed to store the context processor. For examplecontext_processors.py
. Or you can create a dedicatedPython包
, used to store all of the context processor. - In the context processor document you define, define a function that has only one
request
parameter. After this function to handle their own logic, the need to return to the data template, return in the form of a dictionary. If you do not return any data, it must also return an empty dictionary. Sample code is as follows:def frontuser(request): userid = request.session.get("userid") userModel = models.FrontendUser.objects.filter(pk=userid).first() if userModel: return {'frontuser':userModel} else: return {}
Second, the middleware
Middleware is in request
and response
a plug-treatment process. For example, in request
prior to arrival view function, we can use the middleware to do some related things like this can determine the current user has not logged in, if logged in, to bind an user
object to the request
upper. You can also response
before reaching the browser, do something related to treatment, such as unified want in response
on the set some cookie
information.
Custom Middleware:
Middleware position which is not defined. As long as the project is put to them. Two different situations, if the middleware is part of a app
, then this can app
create the following a python
file used to store the middleware can also create a special Python
package, the middleware used to store all of this project. Create middleware, there are two ways, one is to use the function, one is using the class, to be introduced next two manners:
Middleware functions:
def simple_middleware(get_response):
# 这个中间件初始化的代码 def middleware(request): # request到达view的执行代码 response = get_response(request) # response到达浏览器的执行代码 return response return middleware
Middleware class:
class SimpleMiddleware(object):
def __init__(self, get_response): self.get_response = get_response # 这个中间件初始化的代码 def __call__(self, request): # request到达view之前执行的代码 response = self.get_response(request) # response到达用户浏览器之前执行的代码 return response
After writing middleware, also you need settings.MIDDLEWARES
only be configured using the written middleware. For example, we wrote one request
before reaching view function to determine whether the user is logged in, if already logged on a binding user
target to request
middleware on this middleware in the current project middlewares.users
under:
def user_middleware(get_response):
# 这个中间件初始化的代码 def middleware(request): # request到达view的执行代码 userid = request.session.get("userid") userModel = FrontUser.objects.filter(pk=userid).first() if userModel: setattr(request,'frontuser',userModel) response = get_response(request) # response到达浏览器的执行代码 return response return middleware
Then you can settings.MIDDLEWARES
do the following configuration:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'middlewares.users.user_middleware' ]
Implementation of middleware is in order, he will be in accordance MIDDLEWARE
to the execution order stored. So if some other middleware-based middleware is required, then it needs to be placed behind other middleware to execute.
Django built-in middleware:
django.middleware.common.CommonMiddleware
: Universal middleware. His role is as follows:- Limit
settings.DISALLOWED_USER_AGENTS
specified in the request up visit this website.DISALLOWED_USER_AGENT
Is a list of regular expressions. Sample code is as follows:import re DISALLOWED_USER_AGENTS = [ re.compile(r'^\s$|^$'), re.compile(r'.*PhantomJS.*') ]
- If the developer in the definition of
url
the time, and finally there is a slash. But users accessurl
did not submit slash this time, thenCommonMiddleware
will be automatically redirected to add the slashurl
up.
- Limit
django.middleware.gzip.GZipMiddleware
: The response data compression. If the content is shorter than the length of 200, then it will not compress.django.contrib.messages.middleware.MessageMiddleware
: Message handling related middleware.django.middleware.security.SecurityMiddleware
: Security middleware to do some processing. Provided suchXSS
defense request header, such as making thehttp
protocol conversionshttps
work agreements, and the like.django.contrib.sessions.middleware.SessionMiddleware
:session
Middleware. We willrequest
add a good handlesession
object.django.contrib.auth.middleware.AuthenticationMiddleware
: Willrequest
add anuser
object middleware.django.middleware.csrf.CsrfViewMiddleware
:CSRF
Protection of middleware.django.middleware.clickjacking.XFrameOptionsMiddleware
: Doneclickjacking
to protect attacks.clickjacking
Protection attacker on their website virus, write entice users to click a button, and then useiframe
the way to the site of attack by (such as banking sites) to your own website loaded up, and set it to transparent, user can not see, and then attacked the site (such as banking sites) the transfer button to navigate to the site of the virus on the button, so that when the user clicks on the virus site button is actually clicked on the website under attack (such as bank button on the website), enabling the attacker to unknowingly transfer function.- Middleware cache: used for caching some pages.
django.middleware.cache.UpdateCacheMiddleware
。django.middleware.cache.FetchFromCacheMiddleware
。
Built intermediate sequence placed:
SecurityMiddleware
: It should be put first. Because this middleware does not need to rely on any other middleware. If your site supports bothhttp
protocols andhttps
protocol, and you want the user to usehttp
redirection when the protocol tohttps
the agreement, then there is no need for him to perform the following long list of middleware and then redirect more efficient.UpdateCacheMiddleware
: It should be inSessionMiddleware, GZipMiddleware, LocaleMiddleware
before.GZipMiddleware
。ConditionalGetMiddleware
。SessionMiddleware
。LocaleMiddleware
。CommonMiddleware
。CsrfViewMiddleware
。AuthenticationMiddleware
。MessageMiddleware
。FetchFromCacheMiddleware
。FlatpageFallbackMiddleware
。RedirectFallbackMiddleware
。