初始化:所有的Flask都必须创建程序实例,
web服务器使用wsgi协议,把客户端所有的请求都转发给这个程序实例
程序实例是Flask的对象,一般情况下用如下方法实例化
Flask类只有一个必须指定的参数,即程序主模块或者包的名字,__name__是系统变量,该变量指的是本py文件的文件名
Flask 文档
:Flask
类的第一个参数称为 import_name。 它被描述为“应用程序包的名称”。 该文档建议你“通常”通过为此参数传递__name__
来创建 Flask 实例Flask 接受作为
import_name
传递的参数,它是导入包的名称,并尝试使用它通过查找具有该名称的模块对象来确定应用程序的根路径。 一旦知道了这个路径,它就会拼接静态和模板目录名称,这就是它获取这些文件的地方。__name__是一个python内建的系统变量。
- 如果调用
Flask()
将包的名称作为参数传递,那么应用程序的根路径就是包所在的目录。- 如果调用
Flask()
将模块的名称作为参数传递,那么应用程序的根路径就是该模块所在的包的目录。def get_root_path(import_name): """Returns the path to a package or cwd if that cannot be found. This returns the path of a package or the folder that contains a module. Not to be confused with the package path returned by :func:`find_package`. """ # Module already imported and has a file attribute. Use that first. mod = sys.modules.get(import_name) if mod is not None and hasattr(mod, '__file__'): return os.path.dirname(os.path.abspath(mod.__file__)) # Next attempt: check the loader. loader = pkgutil.get_loader(import_name) # Loader does not exist or we're referring to an unloaded main module # or a main module without path (interactive sessions), go with the # current working directory. if loader is None or import_name == '__main__': return os.getcwd() # For .egg, zipimporter does not have get_filename until Python 2.7. # Some other loaders might exhibit the same behavior. if hasattr(loader, 'get_filename'): filepath = loader.get_filename(import_name) else: # Fall back to imports. __import__(import_name) mod = sys.modules[import_name] filepath = getattr(mod, '__file__', None) # If we don't have a filepath it might be because we are a # namespace package. In this case we pick the root path from the # first module that is contained in our package. if filepath is None: raise RuntimeError('No root path can be found for the provided ' 'module "%s". This can happen because the ' 'module came from an import hook that does ' 'not provide file name information or because ' 'it\'s a namespace package. In this case ' 'the root path needs to be explicitly ' 'provided.' % import_name) # filepath is import_name.py for a module, or __init__.py for a package. return os.path.dirname(os.path.abspath(filepath))
通过这个import_name确定Flask这个核心对象被创建的根目录,以获得静态文件和模板文件的目录