@rickyChen
2016-10-09T15:21:04.000000Z
字数 1231
阅读 3400
Python
Django
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
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
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