V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2015-06-15 10:56:26 +08:00 · 3931 次点击
    这是一个创建于 3246 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 条回复    2015-06-15 14:42:28 +08:00
    yuankui
        1
    yuankui  
       2015-06-15 14:42:28 +08:00
    因为函数命名的节操: 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
    但是,他的文件路径却在


    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2328 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 11:04 · PVG 19:04 · LAX 04:04 · JFK 07:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.