gpt4 book ai didi

python - 向装饰器添加参数

转载 作者:太空狗 更新时间:2023-10-30 00:30:45 24 4
gpt4 key购买 nike

我有这个装饰器,如果 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com