Django中间件-排除特定路径

时间:2019-06-16 12:44:28

标签: python django

我已经为Django Web服务器实施了运行状况检查

默认情况下,运行状况检查会调用所有执行缓存失效的中间件,数据库调用,功能标志调用等。

我想避免为此特定路径调用中间件

对于每种中间件,都有__call__方法在执行代码的地方实现

我在哪里可以定义将基于路径执行什么中间件?

1 个答案:

答案 0 :(得分:0)

我针对该问题的解决方案是使用装饰器

def skip_for_paths(paths_to_exclude):
"""
decorator for skipping middleware based on path
"""
def decorator(f):
    def check_if_health(self, request):
        if request.path in paths_to_exclude:
            return self.get_response(request)
        return f(self, request)
    return check_if_health
return decorator

和中间件中的

    @skip_for_paths(['/workflows/v1/health/'])
def __call__(self, request):
    # Code to be executed for each request before

    response = self.get_response(request)

    response['Cache-Control'] = "no-cache"
    # Code to be executed for each request/response after
    # the view is called.