Flask('application') 与 Flask(__name__) [英] Flask('application') versus Flask(__name__)

查看:37
本文介绍了Flask('application') 与 Flask(__name__)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在官方快速入门中,推荐使用__name__ 使用单个模块时:

<块引用>

  1. ...如果您使用单个模块(如本例中),您应该使用 __name__ 因为这取决于它是否作为应用程序或作为模块导入名称会有所不同('__main__' 与实际导入名称)....

但是,在他们的 API 文档中,建议在以下情况下进行硬编码我的应用程序是一个:

<块引用>

因此,您在那里提供的内容很重要.如果您使用单个module, __name__ 总是正确的值.如果你是使用包,通常建议硬编码您的名称在那里打包.

我可以理解为什么最好对我的包的名称进行硬编码,但为什么不对单个模块的名称进行硬编码?或者,换句话说,当Flask接收到一个__main__作为它的第一个参数时,它可以得到什么信息?我看不出这如何让 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:

  1. ... 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 as mypackage/app.py, then using __name__ would tell Flask to look for resources relative to mypackage.app instead of mypackage.

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.

这篇关于Flask('application') 与 Flask(__name__)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆