Flask(__name__)这个参数到底起了什么作用?

2015-08-14 14:18:44 +08:00
 julyclyde
之前文档里说计算相对路径的时候会用到这个,但我试了试好像随便给个什么参数去初始化Flask对象都是一样的结果啊……

除了作为一个属性用来区分多个Flask对象以外,这个初始化参数还能在对象的行为上“起什么作用”?
5238 次点击
所在节点    Flask
2 条回复
niseceric
2015-08-14 23:14:56 +08:00
你可以阅读源码 flask/app.py 里面的Flask类

这只是个应用程序的名字罢了:

.. admonition:: About the First Parameter
The idea of the first parameter is to give Flask an idea of what
belongs to your application. This name is used to find resources
on the filesystem, can be used by extensions to improve debugging
information and a lot more.
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.
For example if your application is defined in :file:`yourapplication/app.py`
you should create it with one of the two versions below::
app = Flask('yourapplication')
app = Flask(__name__.split('.')[0])
Why is that? The application will work even with `__name__`, thanks
to how resources are looked up. However it will make debugging more
painful. Certain extensions can make assumptions based on the
import name of your application. For example the Flask-SQLAlchemy
extension will look for the code in your application that triggered
an SQL query in debug mode. If the import name is not properly set
up, that debugging information is lost. (For example it would only
pick up SQL queries in `yourapplication.app` and not
`yourapplication.views.frontend`)

__name__黑科技主要是下面这个:

@locked_cached_property
def name(self):
"""The name of the application. This is usually the import name
with the difference that it's guessed from the run file if the
import name is main. This name is used as a display name when
Flask needs the name of the application. It can be set and overridden
to change the value.
.. versionadded:: 0.8
"""
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
julyclyde
2015-08-15 18:24:45 +08:00
@niseceric 就是看了This name is used to find resources on the filesystem
但没发现到底怎么use的

def name(self)这个是返回其name吧,注释没看懂,只看懂as a display name了。
求教

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/213201

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX