Python 获取 Flask 应用程序的根路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36649703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:10:08  来源:igfitidea点击:

Get root path of Flask application

pythonflask

提问by thyrel

I'm working on a Flask extension from which I want to create a directory in the project's root path on the file system.

我正在开发一个 Flask 扩展,我想从中创建一个目录,在文件系统的项目根路径中。

Suppose we have this directory structure

假设我们有这个目录结构

/project
    /app
    /tests
    /my_folder
    manage.py

my_folder should be created dynamically by the extension, which is a test utility and wraps the application under test in the /tests directory. However, I'm struggling to determine the project's root path within my extension.

my_folder 应该由扩展程序动态创建,它是一个测试实用程序,将被测应用程序包装在 /tests 目录中。但是,我正在努力确定我的扩展中项目的根路径。

For now, I am trying to guess the path from the run file:

现在,我试图从运行文件中猜测路径:

def root_path(self):
    # Infer the root path from the run file in the project root (e.g. manage.py)
    fn = getattr(sys.modules['__main__'], '__file__')
    root_path = os.path.abspath(os.path.dirname(fn))
    return root_path

This obviously breaks as soon as the tests are run from within the IDE instead of the manage.py. I could simply infer the project's root relative to the app or tests directory, but I don't want to make any assumptions regarding the name or structure of these directories (since multiple apps might be hosted as subpackages in a single package).

一旦测试从 IDE 而不是 manage.py 中运行,这显然会中断。我可以简单地推断项目相对于应用程序或测试目录的根目录,但我不想对这些目录的名称或结构做出任何假设(因为多个应用程序可能作为单个包中的子包托管)。

I was wondering if there is a best practice for this type of problem or an undocumented method which the Flask object provides (such as get_root_path).

我想知道是否有针对此类问题的最佳实践或 Flask 对象提供的未记录方法(例如 get_root_path)。

回答by davidism

app.root_pathcontains the root path for the application. This is determinedbased on the name passed to Flask. Typically, you should use the instance path(app.instance_path) not the root path, as the instance path will not be within the package code.

app.root_path包含应用程序的根路径。这是根据传递给 的名称确定Flask。通常,您应该使用实例路径( app.instance_path) 而不是根路径,因为实例路径不会在包代码中。

filename = os.path.join(app.instance_path, 'my_folder', 'my_file.txt')

回答by Chanpreet Chhabra

app.root_pathis the absolute path to the root directory containing your app code.

app.root_path是包含您的应用程序代码的根目录的绝对路径。

app.instance_pathis the absolute path to the instance folder. os.path.dirname(app.instance_path)is the directory above the instance folder. During development, this is next to or the same as the root path, depending on your project layout.

app.instance_path是实例文件夹的绝对路径。os.path.dirname(app.instance_path)是实例文件夹上方的目录。在开发期间,这与根路径相邻或相同,具体取决于您的项目布局。