不带参数的装饰器
代码语言:javascript
复制from functools import wraps
def object_does_not_exist(func):
@wraps(func)
def returned_wrapper(request, *args, **kwargs):
try:
return func(request, *args, **kwargs)
except ObjectDoesNotExist:
raise Http404()
return returned_wrapper
@object_does_not_exist def detail(request):
"""
用法
"""
pass 123456789101112131415161718
带参数的装饰器
代码语言:javascript
复制def object_does_not_exist(redirect=None):
def decorator(func):
@wraps(func)
def returned_wrapper(request, *args, **kwargs):
try:
return func(request, *args, **kwargs)
except ObjectDoesNotExist:
if redirect:
return HttpResponseRedirect(redirect)
else:
raise Http404()
return returned_wrapper
return decorator
@object_does_not_exist(redirect="/") def detail(request):
pass # 记得加个闭合括号,否则会出现类似 takes exactly 1 argument (0 given) 的错误 @object_does_not_exist() def foo(request):
pass 1234567891011121314151617181920212223
代码语言:javascript
复制def object_does_not_exist(func=None, redirect=None):
def decorator(func):
@wraps(func)
def returned_wrapper(request, *args, **kwargs):
try:
return func(request, *args, **kwargs)
except ObjectDoesNotExist:
if redirect:
return HttpResponseRedirect(redirect)
else:
raise Http404()
return returned_wrapper
if not func:
def foo(func):
return decorator(func)
return foo
else:
return decorator(func)
@object_does_not_exist(redirect="/") def detail(request):
pass @object_does_not_exist def foo(request):
pass