我有以下装饰器,并认为效果很好。

装饰器

def event_admin_only(func):
    """
    Checks if the current role for the user is an Event Admin or not
    """
    def decorator(request, *args, **kwargs):
        event = get_object_or_404(Event, slug=kwargs['event_slug'])

        allowed_roles = [role[1] for role in Role.ADMIN_ROLES]

        # get user current role
        current_role = request.session.get('current_role')

        if current_role not in allowed_roles:
            url = reverse('no_perms')
            return redirect(url)
        else:
            return func(request, *args, **kwargs)
    return decorator

查看
@event_admin_only
def event_dashboard(request, event_slug):
    pass

但是,如何修改修饰器,使其采用如下所示的附加参数:
@event_admin_only(obj1,[...])
def event_dashboard(request, event_slug):
    pass

最佳答案

您需要将装饰器函数的创建包装在另一个函数中:

def the_decorator(arg1, arg2):

    def _method_wrapper(view_method):

        def _arguments_wrapper(request, *args, **kwargs) :
            """
            Wrapper with arguments to invoke the method
            """

            #do something with arg1 and arg2

            return view_method(request, *args, **kwargs)

        return _arguments_wrapper

    return _method_wrapper

然后可以这样称呼它:
@the_decorator("an_argument", "another_argument")
def event_dashboard(request, event_slug):

我建议从e-satis那里得到关于这个问题的答案,以了解这一点:How to make a chain of function decorators?

关于python - Django向装饰器添加可选参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9030255/

10-09 17:13