students who are familiar with web development are sure to be unfamiliar with hook hooks, which can be easily triggered and callback through the hook, and do some filtering and intercepting. Middleware (Middleware) in

django is a kind of hook like existence. Let's give a brief introduction and give some examples.

1, Middleware

></p>
<p>

I steal a map, see a lot of people online to use this map source have been chasing don't understand. To make a brief statement, this picture is not mine. Look at the map we analyze:

1 Django) the corresponding request process: HttpRequest -> RequestMiddleware -> view function -> ResponseMiddleware -> HttpResponse

can see a request to the response process, with the middle of the two middleware request and response process, middleware middleware.

, that is to say, Django provides a mechanism in which

  1. requests arrive at the view function,
  2. view function to response,

supports embedded hooks.

hook features:

  1. global, once you use the middleware, and the release is effective, all requests will go through your embedded middleware.
  2. is sensitive to performance, and if your middleware is poor, it will affect the overall performance of the service.

2 Django Middleware) contains four hook function: process_request/process_view/process_response/process_exception

process_request: after request determine the implementation of the view before

process_view: after determined to be carried out by view view, the real implementation process before and after

process_response:view

process_exceptionview:view

executive executive thrown into the middleware and

are configured in settings.py. The following default configuration, I only intercepted two middleware: SessionMiddleware and CommonMiddleware.

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

,

...) we look at a simple implementation of

 import time from importlib import import_module from django.conf import settings from django.utils.cache import patch_vary_headers from django.utils.http import cookie_date class SessionMiddleware SessionMiddleware (object): def __init__ (self): Engine = import_module (settings.SESSION_ENGINE = engine.SessionStore def process_request (self.SessionStore) self, request: session_key) = request.COOKIES.get (settings.SESSION_COOKIE_NAME, None) request.session = self.SessionStore (session_key) def process_r Esponse (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 if we need # check to delete this cookie. The should be deleted # session 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_v Ary_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 (expires + max_age) = cookie_date (expires_time) the session data and # Save 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=setti Ngs.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH secure=settings.SESSION_COOKIE_SECURE, or None, httponly=settings.SESSION_COOKIE_HTTPONLY or None return response

) can see only the process_request and process_response two default hook function in SessionMiddleware.

let us illustrate the execution of a request with this example. We assume that the scene is like this:

1) from the configuration of two Middleware:SessionMiddleware and CommonMiddleware

(note the order)

2) in each Middleware four process_request/process_view/process_response/ process_exception

hook function to complete the order of execution should be like this:

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 (e.g. It is necessary) to write

11, HttpResponse

2 and Middleware. The way to write

Middleware is very simple:

1) to implement a class, inherit object, and

to rewrite four of the hook functions.

here to focus on a common function.

interceptor / filter (filter)

generally, each request goes through the process_request hook function. In your implementation, there must be two kinds of execution results of the function (you want to do the exception processing yourself)::

1) None

2) HttpResponse object

, if you return to None, the request flow continues to execute, that is, continue to enter other Middleware or hook functions. If

returns to the HttpResponse object, then it returns directly to the page. We can make a blacklist through this function.

to give an example:

pv

 coding:utf-8 -*- # is statistical -*- from datetime import datetime from data_monitor.utils.dbmanager import MysqlManager from data_monitor.common.constant import MYSQL_JOBS as mysql_config class RequestHookMiddleware (object): def process_request (self, request): try: username ('username') = request.COOKIES.get 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

above is the summary of all the content on the Django middleware work flow and writing code examples, I hope to help you. Interested friends can continue to refer to other relevant topics of the station, if there are shortcomings, welcome the message. Thank you for the support of our friends!

you might be interested in this article:


This concludes the body part

This paper fixed link:http://www.script-home.com/django-middleware-workflow-and-writing-example-code.html | Script Home | +Copy Link

Article reprint please specify:Django middleware workflow and writing example code | Script Home

You may also be interested in these articles!