程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Write a Django Middleware

編輯:Python

Realization

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 interviewapp Inside , So the link I introduced is interview.performance.performance_logger_middleware

test

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved