我正在开发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
包含应用程序的根路径。这是determined基于传递给Flask
的名称。通常,您应该使用instance path(app.instance_path
)而不是根路径,因为实例路径不在包代码中。
filename = os.path.join(app.instance_path, 'my_folder', 'my_file.txt')
app.root_path
是包含应用程序代码的根目录的绝对路径。
app.instance_path
是实例文件夹的绝对路径。 os.path.dirname(app.instance_path)
是实例文件夹上方的目录。在开发期间,这与根路径相邻或相同,具体取决于您的项目布局。