python - 向装饰器添加参数

标签 python django decorator

我有这个装饰器,如果 share 参数为 True(由中间件处理),我不想执行 View 时用于装饰 django View

class no_share(object):
    def __init__(self, view):
        self.view = view

    def __call__(self, request, *args, **kwargs):
        """Don't let them in if it's shared"""

        if kwargs.get('shared', True):
            from django.http import Http404
            raise Http404('not availiable for sharing')

        return self.view(request, *args, **kwargs)

目前它是这样工作的:

@no_share
def prefs(request, [...])

但我想稍微扩展一下功能,这样它就可以像这样工作:

@no_share('prefs')
def prefs(request, [...])

我的问题是如何修改这个装饰器类以便它接受额外的参数?

最佳答案

希望this Bruce Eckel 的文章有所帮助。

更新: 根据这篇文章,您的代码将如下所示:

class no_share(object):
    def __init__(self, arg1):
        self.arg1 = arg1

    def __call__(self, f):
        """Don't let them in if it's shared"""

        # Do something with the argument passed to the decorator.
        print 'Decorator arguments:', self.arg1

        def wrapped_f(request, *args, **kwargs):
            if kwargs.get('shared', True):
                from django.http import Http404
                raise Http404('not availiable for sharing')
            f(request, *args, **kwargs)            
        return wrapped_f

根据需要使用:

@no_share('prefs')
def prefs(request, [...])

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

相关文章:

javascript - jquery ajax不提供pdf文件

javascript - AJAX POST 上的 Django [WinError 10053]

python - 以列表为值的字典 - 查找最长列表

python - 如何为此机器学习模型设置 request.py?

python - 使用 Python 脚本从 XML 模式生成 C 头文件

python - django 与 mysql 运行服务器错误

python - 使用 python 装饰器重构代码?

python - 通过装饰器指定模型元数据(django)

python - 2.6 如何在类中定义多参数装饰器

python - 努力理解基于 django 类的 View 代码