• 【Python】Flask中@wraps的使用


      

      先说总结,白话来讲,@wraps相当于是装饰器的装饰器。

      python内置的方法使用解释,看起很复杂的样子┓( ´∀` )┏

    def wraps(wrapped,
              assigned = WRAPPER_ASSIGNMENTS,
              updated = WRAPPER_UPDATES):
        """Decorator factory to apply update_wrapper() to a wrapper function
    
           Returns a decorator that invokes update_wrapper() with the decorated
           function as the wrapper argument and the arguments to wraps() as the
           remaining arguments. Default arguments are as for update_wrapper().
           This is a convenience function to simplify applying partial() to
           update_wrapper().
        """
        return partial(update_wrapper, wrapped=wrapped,
                       assigned=assigned, updated=updated)
    

      

      下面举个栗子:

    from functools import wraps
    
    # 用户角色权限确认
    def permission_required():
        def decorator(f):
            #@wraps(f)
            def decorated_function():
                return 'this is decorated function'
            return decorated_function
        return decorator
    
    # 管理员权限确认
    def admin_required(f):
        return permission_required()(f)
    
    if __name__=='__main__':
        def test_func():
            return 'this is test function'
        print(admin_required(test_func))
    

      

      不用@wraps时,打印出来是酱婶儿的

    <function permission_required.<locals>.decorator.<locals>.decorated_function at 0x00000000030411E0>
    

      

      使用之后看起来清爽了很多

    <function test_func at 0x0000000002FC11E0>
    

      

      通过对比结果,@wraps的作用猜出来个大概。

      使用之后它返回的是参数test_func方法的地址。也就是说,如果你想使用参数方法的一些属性,就需要使用@wraps了。

  • 相关阅读:
    GCC编绎详解
    GUN C/C++ __attribute__ 用法 转
    rust 参考的资料 转
    Eclipse环境安装rust
    GNU Debugger for Windows----GDB
    minGW cygwin gnuwin32
    tdm-gcc
    GNU tools
    The MinGW and mingw-w64 projects.----GCC
    crosstool-NG
  • 原文地址:https://www.cnblogs.com/lilip/p/10755390.html
Copyright © 2020-2023  润新知