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传入的位置