推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
cc7756789
V2EX  ›  Python

flask 当中获得运行 app 脚本的根目录这种写法是否多余

  •  
  •   cc7756789 · Jun 15, 2015 · 4832 views
    This topic created in 4125 days ago, the information mentioned may be changed or developed.

    run.py

    from flask import Flask
    app = Flask(__name__)
    

    flask的源码:

    def _get_package_path(name):
        try:
            return os.path.abspath(os.path.dirname(sys.modules[name].__file__))
        except (KeyError, AttributeError):
            return os.getcwd()
    
    class Flask:
        def __init__(self, name):
            self.name = name
            self.root_path = _get_package_path(self.name)
    

    这其中 _get_package_path 这么写也能获得run.py的根目录:

    def _get_package_path(name):
        try:
            return os.path.abspath(os.path.dirname(name))
        except (KeyError, AttributeError):
            return os.getcwd()
    

    为什么要加上sys.modules[name].__file__

    1 replies  •  2015-06-15 14:42:28 +08:00
    yuankui
        1
    yuankui  
       Jun 15, 2015
    因为函数命名的节操: do what you say,say what you mean

    根据函数命名: 这里是要根据模块名,取得模块文件路径

    而不是仅仅实现一个功能

    另外
    如果出现
    .
    └── hello
    ├── __init__.py
    └── kitty
    ├── __init__.py
    └── real_module.py

    $ cat hello/__init__.py
    import kitty.real_module as real_module

    的情况hello中的real_module虽然叫做hello.real_module
    但是,他的文件路径却在


    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2245 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 00:39 · PVG 08:39 · LAX 17:39 · JFK 20:39
    ♥ Do have faith in what you're doing.