获取Flask应用程序的根路径

时间:2016-04-15 14:20:12

标签: python flask

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

假设我们有这个目录结构

/project
    /app
    /tests
    /my_folder
    manage.py

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

目前,我正在尝试从运行文件中猜测路径:

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

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

我想知道这种类型的问题或Flask对象提供的未记录方法(例如get_root_path)是否存在最佳实践。

2 个答案:

答案 0 :(得分:19)

app.root_path contains the root path for the application. This is determined based 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.

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

答案 1 :(得分:2)

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

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

相关问题