Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refering to a directory in a Flask app doesn't work unless the path is absolute

Tags:

python

flask

nltk

I downloaded nltk data into the data directory in my Flask app. The views reside in a blueprint in another directory on the same level as the data directory. In the view I'm trying to set the path to the data, but it doesn't work.

nltk.data.path.append('../nltk_data/')

This doesn't work. If I use the whole path, it does work.

nltk.data.path.append('/home/username/myapp/app/nltk_data/')

Why does the first form not work? How can I refer to the location of the data correctly?

like image 821
kidman01 Avatar asked May 19 '15 14:05

kidman01


People also ask

What is absolute path in Python?

An absolute file path describes how to access a given file or directory, starting from the root of the file system. A file path is also called a pathname. Relative file paths are notated by a lack of a leading forward slash.

How do you change a relative path to an absolute path in Python?

Use abspath() to Get the Absolute Path in Python abspath() with the given path to get the absolute path. The output of the abspath() function will return a string value of the absolute path relative to the current working directory.

What is send from directory in flask?

flask. send_from_directory (directory, filename, **options)[source] Send a file from a given directory with send_file() . This is a secure way to quickly expose static files from an upload folder or something similar.


1 Answers

In Python (and most languages), where the code resides in a package is different than what the working directory is when running a program. All relative paths are relative to the current working directory, not the code file it's written in. So you would use the relative path nltk_data/ even from a blueprint, or you would use the absolute path and leave no ambiguity.

The root_path attribute on an app (or blueprint) refers to the package directory for the app (or blueprint). Join your relative path to that to get the absolute path.

resource_path = os.path.join(app.root_path, 'enltk_data')

There's probably no reason to be appending this folder every time you call a view. I'm not familiar with nltk specifically, but there's probably a way to structure this so you set up the data path once when you create your app.


project    /    app    /    blueprint
                       /    data

                            ^ join with root_path to get here
                ^ app.root_path always points here, no matter where cwd is
^ current working directory
like image 140
davidism Avatar answered Sep 30 '22 06:09

davidism