# -*-coding:utf-8-*-
__author__ = "GILANG (pleasurelong@foxmail.com)"
"""
django 自定义用于view的装饰器
"""
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):
"""
第二种写法:带参数的装饰器
第二种方法可以解决 got an unexpected keyword argument 错误。
"""
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