Answer a question

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

Answers

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

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐