我想定义一个装饰器,如果满足条件,它将应用another_decorator,
而这只是其他功能。
以下没有工作..
def decorator_for_post(view_func):
@functools.wraps(view_func)
def wrapper(request, *args, **kwargs):
if request.method == 'POST':
return another_decorator(view_func) # we apply **another_decorator**
return view_func # we just use the view_func
return wrapper
答案 0 :(得分:2)
您必须在包装器中实际调用该函数。
return view_func(request, *args, **kwargs)
答案 1 :(得分:2)
你的意思是这样的:
class Request:
def __init__ (self, method):
self.method = method
def another_decorator (f):
print ("another")
return f
def decorator_for_post (f):
def g (request, *args, **kwargs):
if request.method == "POST":
return another_decorator (f) (request, *args, **kwargs)
return f (request, *args, **kwargs)
return g
@decorator_for_post
def x (request):
print ("doing x")
print ("GET")
x (Request ("GET") )
print ("POST")
x (Request ("POST") )