zoukankan      html  css  js  c++  java
  • 55、装饰器的写法以及应用场景。

    应用场景:

    1、授权(Authorization)

    装饰器能有助于检查某个人是否被授权去使用一个web应用的端点(endpoint)。它们被大量使用于Flask和Django web框架中。这里是一个例子来使用基于装饰器的授权:

    from functools import wraps    # 最新版python引用是 import functools
    
    def requires_auth(f):    #  f 就是我们需要装饰的函数,一看就是不带参数的装饰器
        @wraps(f)     # 新版python写法 @functools.wraps(f)
        def decorated(*args, **kwargs):
            auth = request.authorization
            if not auth or not check_auth(auth.username, auth.password):
                authenticate()
            return f(*args, **kwargs)
        return decorated    # 该装饰器需相关配置才能运行,这里是截取代码展示应用

    2.、日志(Logging)

    日志是装饰器运用的另一个亮点。这是个例子:

    from functools import wraps
    
    def logit(func):
        @wraps(func)
        def with_logging(*args, **kwargs):
            print(func.__name__ + " was called")
            return func(*args, **kwargs)
        return with_logging
    
    @logit
    def addition_func(x):
       """Do some math."""
       return x + x
    result = addition_func(4)

    我敢肯定你已经在思考装饰器的一个其他聪明用法了。

    3.、带参数的装饰器

    带参数的装饰器是典型的闭包函数

    4.、在函数中嵌入装饰器

    我们回到日志的例子,并创建一个包裹函数,能让我们指定一个用于输出的日志文件。

    from functools import wraps
    
    def logit(logfile='out.log'):
        def logging_decorator(func):
            @wraps(func)
            def wrapped_function(*args, **kwargs):
                log_string = func.__name__ + " was called"
                print(log_string)
                # 打开logfile,并写入内容
                with open(logfile, 'a') as opened_file:
                    # 现在将日志打到指定的logfile
                    opened_file.write(log_string + '
    ')
                return func(*args, **kwargs)
            return wrapped_function
        return logging_decorator
    @logit()
    def myfunc1():
        pass
    
    myfunc1()
    # Output: myfunc1 was called
    # 现在一个叫做 out.log 的文件出现了,里面的内容就是上面的字符串
    
    @logit(logfile='func2.log')
    def myfunc2():
        pass
    
    myfunc2()
    # Output: myfunc2 was called
    # 现在一个叫做 func2.log 的文件出现了,里面的内容就是上面的字符串

    5.、装饰器类

    现在我们有了能用于正式环境的logit装饰器,但当我们的应用的某些部分还比较脆弱时,异常也许是需要更紧急关注的事情。比方说有时你只想打日志到一个文件。而有时你想把引起你注意的问题发送到一个email,同时也保留日志,留个记录。这是一个使用继承的场景,但目前为止我们只看到过用来构建装饰器的函数。

    幸运的是,类也可以用来构建装饰器。那我们现在以一个类而不是一个函数的方式,来重新构建logit。

  • 相关阅读:
    C# lock
    read appSettings in configuration file by XElement with xmlns
    get all sites under IIS
    Cross-site scripting(XSS)
    Do not throw System.Exception, System.SystemException, System.NullReferenceException, or System.IndexOutOfRangeException intentionally from your own source code
    C++ 算法
    C++ 数据结构概念
    C++ STL 常用算术和生成算法
    C++ STL 常用拷贝和替换算法
    C++ STL 常用排序算法
  • 原文地址:https://www.cnblogs.com/zhuifeng-mayi/p/9231199.html
Copyright © 2011-2022 走看看