如何检查中间件视图上是否存在装饰器

时间:2019-07-18 15:05:46

标签: python django python-3.x python-decorators

我有一个django应用程序,要求将会话设置为具有很多功能,我不想再担心检查是否在视图中设置了会话,因此我将其移至了Midddleware,但是,我仍然有一个很少有需要从中间件中排除的视图。

我已经决定装饰不需要中间件的特定视图,但是我不确定如何检查装饰器是否存在。这可能吗?

到目前为止,我已经尝试将其绑定到请求变量,但这不起作用。

class CheckPropertyMiddleware(object):

    def __init__(self, get_response):
        self.get_response = get_response

    @staticmethod
    def process_view(request, view_func, args, kwargs):
        print(request.property_not_important)
        if not request.session.get('property'):
            print('property not selected')
            messages.error(request, 'You need to select a property to use the system.')
            # return redirect(reverse('home', args=[request.client_url]))
        else:
            print('property selected')

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.
        return response


def property_not_important(function):
    @functools.wraps(function)
    def decorator(request, *args, **kwargs):
        request.property_not_important = True
        return function(request, *args, **kwargs)

    return decorator

1 个答案:

答案 0 :(得分:0)

我想出了一种使用装饰器针对特定视图禁用中间件的解决方案。

这是在视图函数上设置属性并检查其是否存在的方法:

def property_not_important(function):
    """
    Decorator
    """
    orig_func = function
    setattr(orig_func, 'property_not_important', True)

    return function


class ExcludePropertyMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    @staticmethod
    def process_view(request, view_func, view_args, view_kwargs):
        prop_not_important = getattr(view_func, 'property_not_important', False)
        if prop_not_important:
            print('property not important')
            return view_func(request, *view_args, **view_kwargs)
        return None

    def __call__(self, request):
        response = self.get_response(request)
        return response

以下是检查方法名称的解决方案:

class ExcludePropertyMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    @staticmethod
    def process_view(request, view_func, view_args, view_kwargs):
        if view_func.__name__ == "_property_not_important":
            return view_func(request, *view_args, **view_kwargs)
        return None

    def __call__(self, request):
        response = self.get_response(request)
        return response

settings.py

MIDDLEWARE = [
    ...
    'utils.middleware.CheckPropertyMiddleware.ExcludePropertyMiddleware',
    # allow exclusion
    'utils.middleware.CheckPropertyMiddleware.CheckPropertyMiddleware',
]