Python Flask:如何读取应用程序根目录中的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14825787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask: How to read a file in application root?
提问by daydreamer
My Flask application structure looks like
我的 Flask 应用程序结构看起来像
application_top/
application/
static/
english_words.txt
templates/
main.html
urls.py
views.py
runserver.py
When I run the runserver.py, it starts the server at localhost:5000.
In my views.py, I try to open the file english.txtas
当我运行 时runserver.py,它会在localhost:5000. 在我views.py,我尝试打开该文件english.txt作为
f = open('/static/english.txt')
It gives error IOError: No such file or directory
它给出了错误 IOError: No such file or directory
How can I access this file?
我怎样才能访问这个文件?
采纳答案by CppLearner
I think the issue is you put /in the path. Remove /because staticis at the same level as views.py.
我认为问题是你把它/放在了路径上。删除/因为static与 处于同一级别views.py。
I suggest making a settings.pythe same level as views.pyOr many Flask users prefer to use __init__.pybut I don't.
我建议制作settings.py与views.py或许多 Flask 用户喜欢使用的级别相同的级别,__init__.py但我没有。
application_top/
application/
static/
english_words.txt
templates/
main.html
urls.py
views.py
settings.py
runserver.py
If this is how you would set up, try this:
如果这是您的设置方式,请尝试以下操作:
#settings.py
import os
# __file__ refers to the file settings.py
APP_ROOT = os.path.dirname(os.path.abspath(__file__)) # refers to application_top
APP_STATIC = os.path.join(APP_ROOT, 'static')
Now in your views, you can simply do:
现在在您的视图中,您可以简单地执行以下操作:
import os
from settings import APP_STATIC
with open(os.path.join(APP_STATIC, 'english_words.txt')) as f:
f.read()
Adjust the path and level based on your requirement.
根据您的要求调整路径和级别。
回答by jpihl
Here's a simple alternative to CppLearners answer:
这是 CppLearners 答案的一个简单替代方案:
from flask import current_app
with current_app.open_resource('static/english_words.txt') as f:
f.read()
See the documentation here: Flask.open_resource
请参阅此处的文档:Flask.open_resource

