我一直在尝试创建一个可以与Python中的函数和方法一起使用的装饰器。这本身并不难,但是当创建一个带有参数的装饰器时,似乎就很难了。
class methods(object):
def __init__(self, *_methods):
self.methods = _methods
def __call__(self, func):
def inner(request, *args, **kwargs):
print request
return func(request, *args, **kwargs)
return inner
def __get__(self, obj, type=None):
if obj is None:
return self
new_func = self.func.__get__(obj, type)
return self.__class__(new_func)
上面的代码正确包装了函数/方法,但对于方法来说,
request
参数是它正在操作的实例,而不是第一个非 self 参数。
有没有办法判断装饰器是否应用于函数而不是方法,并进行相应的处理?
扩展
__get__
方法。这可以概括为装饰器装饰器。
class _MethodDecoratorAdaptor(object):
def __init__(self, decorator, func):
self.decorator = decorator
self.func = func
def __call__(self, *args, **kwargs):
return self.decorator(self.func)(*args, **kwargs)
def __get__(self, instance, owner):
return self.decorator(self.func.__get__(instance, owner))
def auto_adapt_to_methods(decorator):
"""Allows you to use the same decorator on methods and functions,
hiding the self argument from the decorator."""
def adapt(func):
return _MethodDecoratorAdaptor(decorator, func)
return adapt
通过这种方式,你可以让你的装饰器自动适应它的使用条件。
def allowed(*allowed_methods):
@auto_adapt_to_methods
def wrapper(func):
def wrapped(request):
if request not in allowed_methods:
raise ValueError("Invalid method %s" % request)
return func(request)
return wrapped
return wrapper
请注意,所有函数调用都会调用包装函数,因此不要在那里执行任何昂贵的操作。
装饰器的用法:
class Foo(object):
@allowed('GET', 'POST')
def do(self, request):
print "Request %s on %s" % (request, self)
@allowed('GET')
def do(request):
print "Plain request %s" % request
Foo().do('GET') # Works
Foo().do('POST') # Raises
装饰器总是应用于函数对象——让装饰器
print
其参数的类型,你将能够确认这一点;它通常也应该返回一个函数对象(它已经是一个具有正确__get__
!-的装饰器),尽管后者也有例外。
即,在代码中:
class X(object):
@deco
def f(self): pass
deco(f)
在类主体内调用,并且,当您仍然在那里时,f
是一个函数,而不是方法类型的实例。 (当稍后将 f
作为 __get__
或其实例的属性进行访问时,该方法在 f
的 X
中创建并返回)。
也许您可以更好地解释一下您想要装饰器使用的一种玩具,这样我们就可以提供更多帮助......?
编辑:这也适用于带参数的装饰器,即
class X(object):
@deco(23)
def f(self): pass
然后是在类主体中调用的
deco(23)(f)
,当作为参数传递给任何可调用的 f
返回时,deco(23)
仍然是一个函数对象,并且该可调用仍然应该返回一个函数对象(通常 - 有例外; -).
由于您已经定义了一个
__get__
来在绑定方法上使用装饰器,因此您可以传递一个标志来告诉它是否正在方法或函数上使用。
class methods(object):
def __init__(self, *_methods, called_on_method=False):
self.methods = _methods
self.called_on_method
def __call__(self, func):
if self.called_on_method:
def inner(self, request, *args, **kwargs):
print request
return func(request, *args, **kwargs)
else:
def inner(request, *args, **kwargs):
print request
return func(request, *args, **kwargs)
return inner
def __get__(self, obj, type=None):
if obj is None:
return self
new_func = self.func.__get__(obj, type)
return self.__class__(new_func, called_on_method=True)
这是我发现的检测修饰的可调用对象是否是函数或方法的通用方法:
import functools
class decorator(object):
def __init__(self, func):
self._func = func
self._obj = None
self._wrapped = None
def __call__(self, *args, **kwargs):
if not self._wrapped:
if self._obj:
self._wrapped = self._wrap_method(self._func)
self._wrapped = functools.partial(self._wrapped, self._obj)
else:
self._wrapped = self._wrap_function(self._func)
return self._wrapped(*args, **kwargs)
def __get__(self, obj, type=None):
self._obj = obj
return self
def _wrap_method(self, method):
@functools.wraps(method)
def inner(self, *args, **kwargs):
print('Method called on {}:'.format(type(self).__name__))
return method(self, *args, **kwargs)
return inner
def _wrap_function(self, function):
@functools.wraps(function)
def inner(*args, **kwargs):
print('Function called:')
return function(*args, **kwargs)
return inner
使用示例:
class Foo(object):
@decorator
def foo(self, foo, bar):
print(foo, bar)
@decorator
def foo(foo, bar):
print(foo, bar)
foo(12, bar=42) # Function called: 12 42
foo(12, 42) # Function called: 12 42
obj = Foo()
obj.foo(12, bar=42) # Method called on Foo: 12 42
obj.foo(12, 42) # Method called on Foo: 12 42
我提出的部分(特定)解决方案依赖于异常处理。我正在尝试创建一个装饰器以仅允许某些 HttpRequest 方法,但使其与视图函数和视图方法一起使用。
所以,这个类将做我想做的事:
class methods(object):
def __init__(self, *_methods):
self.methods = _methods
def __call__(self, func):
@wraps(func)
def inner(*args, **kwargs):
try:
if args[0].method in self.methods:
return func(*args, **kwargs)
except AttributeError:
if args[1].method in self.methods:
return func(*args, **kwargs)
return HttpResponseMethodNotAllowed(self.methods)
return inner
以下是两个用例: 装饰函数:
@methods("GET")
def view_func(request, *args, **kwargs):
pass
以及类的装饰方法:
class ViewContainer(object):
# ...
@methods("GET", "PUT")
def object(self, request, pk, *args, **kwargs):
# stuff that needs a reference to self...
pass
有比使用异常处理更好的解决方案吗?
为什么不传递一个参数,在所有情况下都有效
def test(ignore_first=False):
def decorator(func):
if not ignore_first:
def _func(x):
# do something
return func(x)
else:
def _func(_,x):
# do something
return func(_,x)
return _func
return decorator