stay app I'll build a new one performance.py
file , Used to define our middleware functions , The function implemented here is to record the access time of the page .
import time
import logging
logger = logging.getLogger(__name__)
def performance_logger_middleware(get_response):
def middleware(request):
# Calculating the response takes
start_time = time.time()
response = get_response(request)
duration = time.time() - start_time
# stay response header Write page access time-consuming properties in
response["X-Page-Duration-ms"] = int(duration * 1000)
# Load log
logger.info("%s %s %s", duration, request.path, request.GET.dict() )
return response
return middleware
Later on django The middleware is registered in the project settings file , my performance.py
File is created in interview
app Inside , So the link I introduced is interview.performance.performance_logger_middleware
Here I have set up the log to print to the command line and write to the log file , Please refer to django Log section in the document .
thus , A simple middleware is implemented , alike , You can also use the method class of a class to define a middleware ( You can refer to django Source code of Middleware , The middleware is defined based on the method classes of classes ), The method definition of function used in this example is just for convenience .