瓶('应用程序')与瓶(__名___) [英] Flask('application') versus Flask(__name__)
问题描述
在快速入门中,建议使用 __ name __
在使用单个模块时:
- ...如果您使用的是单个模块(如本例所示),您应该使用
__ name __
,因为取决于作为
应用程序启动或作为模块导入,名称将与实际导入名称不同
('__ main __'
>)。 ...
然而,在 API文档,当我的应用程序是包时,建议使用硬编码。
$ b
所以你在那里提供的是很重要的。如果您使用的是单个
模块,则__ name __
总是正确的值。如果你是使用一个包的
,通常建议在那里硬编码
包的名字。 >我可以理解为什么硬编码我的包的名称更好,但为什么不硬编码单个模块的名称?换句话说,当它收到一个__ main __
作为第一个参数时,Flask
会得到什么样的信息?我看不出这是如何让Flask更容易找到资源的。
__ name __
只是获取应用程序定义位置的导入名称的简便方法。 Flask使用导入名称来知道在哪里查找资源,模板,静态文件,实例文件夹等。使用包时,如果您在__ init __。py
那么__ name __
仍将指向相对于资源所在的正确位置。但是,如果你在其他地方定义它,例如mypackage / app.py
,那么使用__ name __
会告诉Flask相对于mypackage.app
而不是mypackage
。
<使用__ name __
与硬编码不是正交的,它只是使用包的名称的一个快捷方式。也没有理由说名称应该是基本包,完全取决于您的项目结构。In the official Quickstart, it's recommended to use
__name__
when using a single module:
- ... If you are using a single module (as in this example), you should use
__name__
because depending on if it’s started as application or imported as module the name will be different ('__main__'
versus the actual import name). ...
However, in their API document, hardcoding is recommended when my application is a package:
So it’s important what you provide there. If you are using a single module,
__name__
is always the correct value. If you however are using a package, it’s usually recommended to hardcode the name of your package there.I can understand why it's better to hardcode the name of my package, but why not hardcoding the name of a single module? Or, in other words, what information can
Flask
get when it receives a__main__
as its first parameter? I can't see how this can make it easier for Flask to find the resources...解决方案
__name__
is just a convenient way to get the import name of the place the app is defined. Flask uses the import name to know where to look up resources, templates, static files, instance folder, etc. When using a package, if you define your app in__init__.py
then the__name__
will still point at the "correct" place relative to where the resources are. However, if you define it elsewhere, such asmypackage/app.py
, then using__name__
would tell Flask to look for resources relative tomypackage.app
instead ofmypackage
.Using
__name__
isn't orthogonal to "hardcoding", it's just a shortcut to using the name of the package. And there's also no reason to say that the name should be the base package, it's entirely up to your project structure.这篇关于瓶('应用程序')与瓶(__名___)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!