The context processor and Django middleware

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_processorsthe, has many built-context processor. The context processor acting as follows:

  1. django.template.context_processors.debug: Add a debugand sql_queriesvariable. In the template you can view some database query by him.
  2. django.template.context_processors.request: Add a requestvariable. This requestvariable is the first argument to the view function.
  3. django.contrib.auth.context_processors.auth: DjangoThere are built-in user systems, this processor will add a context userobject.
  4. django.contrib.messages.context_processors.messages: Add a messagesvariable.
  5. django.template.context_processors.media: It can be read in the template MEDIA_URL. For example, you want to use in the template file to upload, then you need to use this time settings.pyset MEDIA_URLto splice url. Sample code is as follows:
    <img src="" />
    
  6. django.template.context_processors.static: You can use the template STATIC_URL.
  7. django.template.context_processors.csrf: You can use the template csrf_tokenvariables to generate a csrf 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:

  1. You can be the basis of this context processor belongs app, then this appcreates a document designed to store the context processor. For example context_processors.py. Or you can create a dedicated Python包, used to store all of the context processor.
  2. In the context processor document you define, define a function that has only one requestparameter. 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 requestand responsea plug-treatment process. For example, in requestprior 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 userobject to the requestupper. You can also responsebefore reaching the browser, do something related to treatment, such as unified want in responseon the set some cookieinformation.

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 appcreate the following a pythonfile used to store the middleware can also create a special Pythonpackage, 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.MIDDLEWARESonly be configured using the written middleware. For example, we wrote one requestbefore reaching view function to determine whether the user is logged in, if already logged on a binding usertarget to requestmiddleware on this middleware in the current project middlewares.usersunder:

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.MIDDLEWARESdo 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 MIDDLEWAREto 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:

  1. django.middleware.common.CommonMiddleware: Universal middleware. His role is as follows:
    • Limit settings.DISALLOWED_USER_AGENTSspecified in the request up visit this website. DISALLOWED_USER_AGENTIs 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 urlthe time, and finally there is a slash. But users access urldid not submit slash this time, then CommonMiddlewarewill be automatically redirected to add the slash urlup.
  2. django.middleware.gzip.GZipMiddleware: The response data compression. If the content is shorter than the length of 200, then it will not compress.
  3. django.contrib.messages.middleware.MessageMiddleware: Message handling related middleware.
  4. django.middleware.security.SecurityMiddleware: Security middleware to do some processing. Provided such XSSdefense request header, such as making the httpprotocol conversions httpswork agreements, and the like.
  5. django.contrib.sessions.middleware.SessionMiddleware: sessionMiddleware. We will requestadd a good handle sessionobject.
  6. django.contrib.auth.middleware.AuthenticationMiddleware: Will requestadd an userobject middleware.
  7. django.middleware.csrf.CsrfViewMiddleware: CSRFProtection of middleware.
  8. django.middleware.clickjacking.XFrameOptionsMiddleware: Done clickjackingto protect attacks. clickjackingProtection attacker on their website virus, write entice users to click a button, and then use iframethe 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.
  9. Middleware cache: used for caching some pages.
    • django.middleware.cache.UpdateCacheMiddleware
    • django.middleware.cache.FetchFromCacheMiddleware

Built intermediate sequence placed:

  1. SecurityMiddleware: It should be put first. Because this middleware does not need to rely on any other middleware. If your site supports both httpprotocols and httpsprotocol, and you want the user to use httpredirection when the protocol to httpsthe agreement, then there is no need for him to perform the following long list of middleware and then redirect more efficient.
  2. UpdateCacheMiddleware: It should be in SessionMiddleware, GZipMiddleware, LocaleMiddlewarebefore.
  3. GZipMiddleware
  4. ConditionalGetMiddleware
  5. SessionMiddleware
  6. LocaleMiddleware
  7. CommonMiddleware
  8. CsrfViewMiddleware
  9. AuthenticationMiddleware
  10. MessageMiddleware
  11. FetchFromCacheMiddleware
  12. FlatpageFallbackMiddleware
  13. RedirectFallbackMiddleware。        

Guess you like

Origin www.cnblogs.com/fisherbook/p/11068579.html