** 2/28 Fixed forgetting to upload files to the repository. .. .. ** **
Create and use your own middleware with Django.
Pre-processing and request processing in the view Request and response are processed as post-processing of view.
middlewares
|_ __init__.py
|_ sample_middleware.py
sample_middleware.py
class SampleMiddleware(object):
"""
Sample middleware,
Before the request is processed by view and
Just display the string on the screen before the response is returned to the client
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
self.process_request(request) #Preprocessing
response = self.get_response(request) #View processing
self.process_response(request, response) #Post-processing
return response
def process_request(self, request):
print("Request processing")
def process_response(self, request, response):
print("Response processing")
The routing and view preparation are appropriate. Any pre-processing and post-processing methods can be added (Of course it doesn't have to be process_ ~~)
settings.Excerpt from py
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',
'middleware_sample.middlewares.sample_middleware.SampleMiddleware',
]
When you access http://127.0.0.1:8000/test/ with a browser, The following contents are displayed.
Display of server-side terminal when accessing the browser
Request processing
Processing view for Sample
Response processing
[27/Feb/2017 14:11:02] "GET /test/ HTTP/1.1" 200 22
I have posted the sample code on GitHub https://github.com/Fufuhu/DjangoMiddlewareSample
Recommended Posts