如何使用装饰器禁用某些功能的中间件?

时间:2017-06-08 22:17:45

标签: python django

我想模仿csrf_exempt的行为(请参阅herehere)。遵循CSRF中间件方式的问题在于它使用了from django.utils.deprecation import MiddlewareMixin,这是不推荐使用的。有没有办法在Django 1.11中使用recommended way创建中间件来实现这一点?我也知道from django.utils.decorators import decorator_from_middleware,但这与我想要的相反。有人有什么想法吗?

编辑:以下有效,但不是最漂亮的建议吗?

class MyMiddleware(object):
    def __init(self, get_response):
        # initialization

    def process_view(self, request, view_func, view_args, view_kwargs):
        if getattr(view_func, "my_middleware_exempt", False):
            request.exempt = True
            return None

        # Perform request logic

    def __call__(self, request):
        # __call__ has to be included, even though I don't want it.
        response = self.get_response(request)
        # If I wanted to perform logic after the request,
        # I would have to check the flag I set on the request
        # in process_view
        if not request.exempt:
            # perform logic
        return response

def exempt_decorator(f):
    @wraps(f)
    def decorator(*args, **kwargs):
        return f(*args, **kwargs)
    decorator.my_middleware_exempt = True
    return decorator

0 个答案:

没有答案