Django middleware workflow and writing example code, django Middleware

Source: Internet
Author: User

Django middleware workflow and writing example code, django Middleware

Those familiar with web development are certainly familiar with hook hooks. They can easily implement some triggers and callbacks and perform some filtering and interception.

Middleware (middleware) in django is a kind of hooks. Next we will introduce some instances.

1. Middleware Workflow

I have stolen a picture, and many people on the internet use this picture, and the source is no longer clear. Simply declare that this image is not mine. Let's look at the figure and analyze it:

1) django request process: HttpRequest-> RequestMiddleware-> view function-> ResponseMiddleware-> HttpResponse

We can see a request-to-Response Process with two middleware processes in the middle, request middleware and response middleware.

That is to say, django provides a mechanism in:

  1. Request arrives at the center of the view Function
  2. Between view functions and responses

Supports embedded hooks.

Features of this HOOK:

  1. Global, once you use middleware and the release takes effect, all requests will go through the middleware you have embedded.
  2. Performance-sensitive. If your middleware has poor performance, it will affect the overall performance of the service.

2) django's middleware contains four hook functions: process_request/process_view/process_response/process_exception

process_request: After receiving the request, determine the view to be executed.

process_view: After determining the view to be executed, before the view is actually executed

process_response: View after execution

process_exceptionview: View execution throws an exception

The middleware insertion process is configured in settings. py. The default configuration is as follows. I only have two middleware: SessionMiddleware and CommonMiddleware.

MIDDLEWARE_CLASSES = (  'django.contrib.sessions.middleware.SessionMiddleware',  'django.middleware.common.CommonMiddleware',    ...    )

Let's take a brief look.SessionMiddlewareImplementation

import timefrom importlib import import_modulefrom django.conf import settingsfrom django.utils.cache import patch_vary_headersfrom django.utils.http import cookie_dateclass SessionMiddleware(object):  def __init__(self):    engine = import_module(settings.SESSION_ENGINE)    self.SessionStore = engine.SessionStore  def process_request(self, request):    session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)    request.session = self.SessionStore(session_key)  def process_response(self, request, response):    """    If request.session was modified, or if the configuration is to save the    session every time, save the changes and set a session cookie or delete    the session cookie if the session has been emptied.    """    try:      accessed = request.session.accessed      modified = request.session.modified      empty = request.session.is_empty()    except AttributeError:      pass    else:      # First check if we need to delete this cookie.      # The session should be deleted only if the session is entirely empty      if settings.SESSION_COOKIE_NAME in request.COOKIES and empty:        response.delete_cookie(settings.SESSION_COOKIE_NAME)      else:        if accessed:          patch_vary_headers(response, ('Cookie',))        if modified or settings.SESSION_SAVE_EVERY_REQUEST:          if request.session.get_expire_at_browser_close():            max_age = None            expires = None          else:            max_age = request.session.get_expiry_age()            expires_time = time.time() + max_age            expires = cookie_date(expires_time)          # Save the session data and refresh the client cookie.          # Skip session save for 500 responses, refs #3881.          if response.status_code != 500:            request.session.save()            response.set_cookie(settings.SESSION_COOKIE_NAME,                request.session.session_key, max_age=max_age,                expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,                path=settings.SESSION_COOKIE_PATH,                secure=settings.SESSION_COOKIE_SECURE or None,                httponly=settings.SESSION_COOKIE_HTTPONLY or None)    return response

You can see inSessionMiddlewareOnlyprocess_requestAndprocess_responseTwo hook functions.

This example describes the execution process of the next request. We assume that the scenario is as follows:

1) configure two Middleware (attention sequence): SessionMiddleware and CommonMiddleware.

2) The four hook functions in each Middleware are complete.process_request/process_view/process_response/process_exception

The execution sequence is as follows:

1. HttpRequest

2. SessionMiddleware process_request

3. SessionMiddleware process_view

4. CommonMiddleware process_request

5. CommonMiddleware process_view

6. view

7. CommonMiddleware process_response

8. CommonMiddleware process_exception (if necessary)

9. SessionMiddleware process_response

10. SessionMiddleware process_exception (if necessary)

11. HttpResponse

2. Middleware:

1) implement a class and inherit the object;

2) rewrite the four hook functions.

Here we will focus on a common function.

Interceptor/filter)

In general, every request must go throughprocess_requestThis hook function. In your implementation, there must be two types of function execution results (you need to handle exceptions yourself ):

1) None

2) HttpResponse object

If None is returned, the request process continues to run, that is, it continues to enter other Middleware or hook functions.

If the HttpResponse object is returned, it is directly returned to the page. We can use this function as a blacklist.

Here is an example:

Statistics pv

# -*- coding:utf-8 -*-from datetime import datetimefrom data_monitor.utils.dbmanager import MysqlManagerfrom data_monitor.common.constant import MYSQL_JOBS as mysql_configclass RequestHookMiddleware(object):  def process_request(self, request):    try:      username = request.COOKIES.get('username')      uri = request.path      timestamp = str(datetime.now())      db_obj = MysqlManager(        mysql_config.get('host'),        mysql_config.get('port'),        mysql_config.get('db'),        mysql_config.get('user'),        mysql_config.get('password'),        format=True,      )      field_str = 'username, uri, timestamp'      value_str = '"%s","%s","%s"' % (username, uri, timestamp)      db_obj.insert('pv', field_str, value_str)      db_obj.close()      return    except Exception, ex:      return
Summary

The above is all the content of this article on the workflow of Django middleware and the sample code written. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.