Flask类

Flask类源码解析

Flask类的init方法:

def __init__(
       self,
       import_name,
       static_url_path=None,
       static_folder='static',
       static_host=None,
       host_matching=False,
       subdomain_matching=False,
       template_folder='templates',
       instance_path=None,
       instance_relative_config=False,
       root_path=None
   ):

在实例Flask对象时,通常语句是这样的:

app = Flask(__name__)

可以看到__name__是传给了import_name,处理import_name的代码:

  @locked_cached_property
  def name(self):
      if self.import_name == '__main__':
          fn = getattr(sys.modules['__main__'], '__file__', None)
          if fn is None:
              return '__main__'
          return os.path.splitext(os.path.basename(fn))[0]
      return self.import_name

getattr(object, name[, default]) -> value

getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.

sys.modules

sys.modules 是一个全局字典,Python启动后建立在内存中。作用是记录导入的模块。在第二次导入同一个模块时,Python会直接到字典中查找,从而加快了程序运行的速度。

print(sys.modules[__name__])
打印结果:
<module '__main__' from 'D:/python自动化21/untitled/07/上课/序列化.py'>

__file__ :脚本所在的路径

os.path.basename(p)

Returns the final component of a pathname

os.path.splitext(p)

返回数组['路径到文件名','扩展名']

Split a path in root and extension.

The extension is everything starting at the last dot in the last pathname component;

the root is everything before that.
It is always true that root + ext == p.

**所以 如果传入的__name__ == '__main__'

返回的值是该模块的名字**

装饰器locked_cached_property

class locked_cached_property(object):
    """A decorator that converts a function into a lazy property.  The
    function wrapped is called the first time to retrieve the result
    and then that calculated result is used the next time you access
    the value.  Works like the one in Werkzeug but has a lock for
    thread safety.
    """

    def __init__(self, func, name=None, doc=None):
        self.__name__ = name or func.__name__
        self.__module__ = func.__module__
        self.__doc__ = doc or func.__doc__
        self.func = func
        self.lock = RLock()

    def __get__(self, obj, type=None):
        if obj is None:
            return self
        with self.lock:
            value = obj.__dict__.get(self.__name__, _missing)
            if value is _missing:
                value = self.func(obj)
                obj.__dict__[self.__name__] = value
            return value

这个是类装饰器,func即是函数name传入的位置

转载于:https://www.cnblogs.com/ravener/p/9807049.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值