“Flask MegaTutorial”如何从上面的包根加载配置?

2024-09-30 18:33:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我指的是The Flask Mega-TutorialGithub Repo中的这段代码

flasky/
    app.py
    config.py
    app/
        __init__.py
        ...
    ...

有一句话我不能完全理解

#__init__.py
...
from config import config
...
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    ...
...

它如何从包根目录外的config.py文件导入?你知道吗

我确实找到了一个Dockerfile带有以下条目

COPY flasky.py config.py boot.sh ./

这是什么意思?这一行是否以某种方式将这些文件添加到路径中? 为什么不把config.py文件放在/app文件夹中呢?你知道吗


Tags: 文件the代码namefrompyimportconfig
1条回答
网友
1楼 · 发布于 2024-09-30 18:33:19

在Github上也有同样的问题,Miguel回答了这个问题: https://github.com/miguelgrinberg/flasky/issues/154#issuecomment-395907521

引用:

The config module is found because it is in the current directory. It does not matter from where it is imported, the fully qualified location for that module is just the module name. This is actually the same reason why you can say from app import .... The app package is found because it is in the current directory, same as config. Hope this clarifies it.

再往下看:

You have a misunderstanding of what "current directory" means. The current directory is an operating system concept, each process has a directory that is marked as the current directory. By default, the current directory for a process is the directory from where the application was started (but the application itself can change this if it wants to). In this case, you start the application from the flasky directory, right? So that is your current directory. From any Python modules you can import config and app without problem, because the current directory is in the Python import path.

希望有帮助。你知道吗

相关问题 更多 >