Django analysis-Middleware, djangomiddleware
After writing scripts for a few weeks, I finally started to access the web framework ~ And then get rid of the version number in the request. Why? In this case, the path of the static file output at the front end will be added with the version number. In this way, when a new static file is developed, the client will forcibly refresh the local cache, to achieve this goal, you must first configure it in the settings file, so that you can directly read the version number from the settings file each time you modify it. The following is a rough process. Feel it for yourself ~
# Static file version numberSTATIC_VERSION = 'v1124'
Then, you can get this variable in the views file of the app whose version number you want to use and assign it to the template to be rendered.
# To retrieve variables in the settings file, you must first import the module from django. conf import settings # obtain the static file version = settings in the settings configuration file. STATIC_VERSION # The following function is an example ..... def index (request): template = loader. get_template ('base/base_index.html ') # pass the obtained static file version number to the template context = Context ({'version': version}) return HttpResponse (template. render (context ))
In this way, you can write the static file path in the HTML file.
<link rel="stylesheet" type="text/css" href="/youappname/static/css/css.{{version}}.css"><script language="javascript" type="text/javascript" src="/youappname/static/js/script.{{version}}.js"></script>
In this step, when you open the browser background, you will find that your path will change, however, when you refresh the file again, the static file cannot be found. Why? At this time, the browser will continue to request static files according to the new path, but you will find that the physical address of your static files has not changed, so what should we do if you request a new address and naturally cannot get it?
The following figure shows Middleware! What is Middleware? The document says it is middleware, which may not be easy to understand. It is actually the interceptor in Struts2 in the Javaweb framework, and its functions and principles are exactly the same, in this way, we can understand Middleware in Django. Since it is an interceptor, it is not just as simple as filtering a static file version, after reading the document, I found that there are many practical functions. What can be done?
Process_request: after receiving the request, determine the view to be executed.
Process_view: After the view to be executed is determined, the view is before it is actually executed.
After process_response view execution
Process_exception (self, request, exception) view throws an exception
By inheriting and implementing one or more methods above, we can implement the functions we want. What about its processing process? Naturally, it is the same as the interceptor.
MIDDLEWARE_CLASSES = ('django. middleware. common. commonMiddleware ', 'django. contrib. sessions. middleware. sessionMiddleware ', 'django. middleware. csrf. csrfViewMiddleware ', 'django. contrib. auth. middleware. authenticationMiddleware ', 'django. contrib. messages. middleware. messageMiddleware ', # the following address is the 'youappname. pyname. calssname ',)
Now that we have installed our middleware, we can intercept all request requests. Now we should process our business logic in the middleware.
# Coding = utf-8import urllib, pdb, refrom django. template import RequestContextfrom django. shortcuts import render_to_responseclass middlewareVersion (object): def process_request (self, request): # if the url request contains the request of the current file, it is intercepted if request. path_info.startswith ('/youappname/static/'): # obtain the path and use the regular expression to filter out the request. path_info = re. sub (R '\. v \ d + ', '', request. path_info)
Because my version number starts with v and is followed by a number, use regular expressions to replace such a string with null.
Now, are we done according to the previous flowchart? Apparently not ~ In this case, you will find that your Middleware does not work. We use pdb for breakpoint debugging. In fact, we have not captured the request for static files. Why? Because it's a system app!
INSTALLED_APPS = ('django. contrib. auth ', 'django. contrib. contenttypes ', 'django. contrib. sessions ', 'django. contrib. sites ', 'django. contrib. messages ', # Is the following app 'django. contrib. staticfiles ', # Uncomment the next line to enable the admin: # 'django. contrib. admin', # Uncomment the next line to enable admin documentation: # 'django. contrib. admindocs ',)
If no static path is configured, the system sends all static file requests to staticfiles by default, so we need to stop the app, in this way, the request can be received perfectly. Since Baidu does not provide the Routing File configuration method for many methods, the results will be incorrect, so I posted the configuration method in the route.
static_dir = os.path.join(os.path.dirname(__file__),'../youappname/static')urlpatterns += patterns('', (r'^youappname/static/(?P<path>.*)$','django.views.static.serve',{'document_root':static_dir}),)
In this way, there should be no major problems. Perfect reception !!!
Today's work is complicated and complicated. In order to implement this small function, I have tried and tried again. It turns out that poor English really hurts T.T ..... This is the end of the evening. Next time you have the opportunity to write some other small functions.