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

查看:86
本文介绍了获取 Flask 应用程序的根路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

假设我们有这个目录结构

/项目/应用程序/测试/我的文件夹管理文件

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

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

def root_path(self):# 从项目根目录中的运行文件推断根路径(例如 manage.py)fn = getattr(sys.modules['__main__'], '__file__')root_path = os.path.abspath(os.path.dirname(fn))返回 root_path

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

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

解决方案

app.root_path 包含应用程序的根路径.这是根据传递给的名称确定烧瓶.通常,您应该使用实例路径 (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天全站免登陆