[关闭]
@rickyChen 2016-10-09T15:21:04.000000Z 字数 1231 阅读 3400

Django自定义用于Views的装饰器

Python Django


不带参数的装饰器

  1. from functools import wraps
  2. def object_does_not_exist(func):
  3. @wraps(func)
  4. def returned_wrapper(request, *args, **kwargs):
  5. try:
  6. return func(request, *args, **kwargs)
  7. except ObjectDoesNotExist:
  8. raise Http404()
  9. return returned_wrapper
  10. @object_does_not_exist
  11. def detail(request):
  12. """
  13. 用法
  14. """
  15. pass

带参数的装饰器

  1. def object_does_not_exist(redirect=None):
  2. def decorator(func):
  3. @wraps(func)
  4. def returned_wrapper(request, *args, **kwargs):
  5. try:
  6. return func(request, *args, **kwargs)
  7. except ObjectDoesNotExist:
  8. if redirect:
  9. return HttpResponseRedirect(redirect)
  10. else:
  11. raise Http404()
  12. return returned_wrapper
  13. return decorator
  14. @object_does_not_exist(redirect='/')
  15. def detail(request):
  16. pass
  17. # 记得加个闭合括号,否则会出现类似 takes exactly 1 argument (0 given) 的错误
  18. @object_does_not_exist()
  19. def foo(request):
  20. pass
  1. def object_does_not_exist(func=None, redirect=None):
  2. def decorator(func):
  3. @wraps(func)
  4. def returned_wrapper(request, *args, **kwargs):
  5. try:
  6. return func(request, *args, **kwargs)
  7. except ObjectDoesNotExist:
  8. if redirect:
  9. return HttpResponseRedirect(redirect)
  10. else:
  11. raise Http404()
  12. return returned_wrapper
  13. if not func:
  14. def foo(func):
  15. return decorator(func)
  16. return foo
  17. else:
  18. return decorator(func)
  19. @object_does_not_exist(redirect='/')
  20. def detail(request):
  21. pass
  22. @object_does_not_exist
  23. def foo(request):
  24. pass

原文出处

python django 自定义 装饰器

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注