julyclyde
V2EX  ›  Flask

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

  •  
  •   julyclyde ·
    julyclyde · Aug 14, 2015 · 6017 views
    This topic created in 3925 days ago, the information mentioned may be changed or developed.
    之前文档里说计算相对路径的时候会用到这个,但我试了试好像随便给个什么参数去初始化Flask对象都是一样的结果啊……

    除了作为一个属性用来区分多个Flask对象以外,这个初始化参数还能在对象的行为上“起什么作用”?
    2 replies    2015-08-15 18:24:45 +08:00
    niseceric
        1
    niseceric  
       Aug 14, 2015   ❤️ 1
    你可以阅读源码 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
        2
    julyclyde  
    OP
       Aug 15, 2015
    @niseceric 就是看了This name is used to find resources on the filesystem
    但没发现到底怎么use的

    def name(self)这个是返回其name吧,注释没看懂,只看懂as a display name了。
    求教
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3309 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 11:46 · PVG 19:46 · LAX 04:46 · JFK 07:46
    ♥ Do have faith in what you're doing.