Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Get root path of Flask application

Writer Andrew Mclaughlin

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

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

app.root_path is the absolute path to the root directory containing your app code.

app.instance_path is the absolute path to the instance folder. os.path.dirname(app.instance_path) is the directory above the instance folder. During development, this is next to or the same as the root path, depending on your project layout.

0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy