Loading... ## 实现 在app里新建一个`performance.py`文件,用来定义我们的中间件函数,这里实现的函数功能为记录页面的访问时间。 ```python import time import logging logger = logging.getLogger(__name__) def performance_logger_middleware(get_response): def middleware(request): # 计算响应耗时 start_time = time.time() response = get_response(request) duration = time.time() - start_time # 在response header中写入页面访问耗时的属性 response["X-Page-Duration-ms"] = int(duration * 1000) # 载入日志 logger.info("%s %s %s", duration, request.path, request.GET.dict() ) return response return middleware ``` 随后在django项目设置文件里面注册中间件,我的`performance.py`文件是创建在`interview`app里面的,所以我引入的链接为`interview.performance.performance_logger_middleware`  ## 测试 这里我已经设置了将日志打印至命令行以及写入日志文件,具体配置请查看django文档中日志部分。    至此,一个简单的中间件就实现了,同样的,也可以使用类的方法类定义一个中间件(可以参考django中间件的源码,都是基于类的方法类定义中间件的),本文例子中使用函数的方法定义只是为了方便。 Last modification:December 24th, 2020 at 07:38 pm © 允许规范转载