引用Flask应用程序中的目录不起作用,除非路径是绝对路径 [英] Refering to a directory in a Flask app doesn't work unless the path is absolute
问题描述
nltk.data。 path.append('../ nltk_data /')
这是行不通的。
nltk.data.path.append('/ home / username / myapp / app / nltk_data /')
为什么第一个表单不起作用?如何正确地引用数据的位置?
在Python中(和大多数语言),代码驻留在程序包与运行程序时的工作目录不同。所有的相对路径都是相对于当前的工作目录,而不是它写入的代码文件。所以,即使是从蓝图中也可以使用相对路径 nltk_data /
应用程序(或蓝图)上的 root_path
属性是指包应用程序(或蓝图)的目录。
resource_path = os.path.join(app.root_path,'enltk_data ')
可能没有理由追加这个每次你打电话查看文件夹。我不是特别熟悉nltk,但是可能有一种方法来构造这个,所以当你创建你的应用程序的时候,你需要设置一次数据路径。
$ prefb =lang-none prettyprint-override>
项目/ app / blueprint
/ data
^加入root_path到达
^ app.root_path总是指向这里,无论哪里cwd是
^当前工作目录
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?
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
这篇关于引用Flask应用程序中的目录不起作用,除非路径是绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!