zoukankan      html  css  js  c++  java
  • python django 自定义 装饰器

    # -*-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
    

      

  • 相关阅读:
    渗透测试-实用版
    微观传输原理:协议、端口、套接字接口
    如何暂停和继续运行Linux程序
    QUIC:基于udp的传输新技术
    ops运维工具
    日志监控工具安装:windows上安装elk
    python实现图片隐藏信息技术
    让网站不去请求favicon.ico图标
    nginx 内核优化
    nginx 模块介绍
  • 原文地址:https://www.cnblogs.com/zhaojia-dream/p/4673779.html
Copyright © 2011-2022 走看看