获取Flask应用程序的根路径 [英] Get root path of Flask application

查看:234
本文介绍了获取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).

解决方案

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

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

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.

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.

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).

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).

解决方案

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')

这篇关于获取Flask应用程序的根路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆