Flask:如何在应用程序根目录中读取文件? [英] Flask: How to read a file in application root?

查看:510
本文介绍了Flask:如何在应用程序根目录中读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Flask应用程序结构如下

My Flask application structure looks like

application_top/
         application/
                    static/
                          english_words.txt
                    templates/
                             main.html
                     urls.py
                     views.py
         runserver.py

当我运行runserver.py时,它将在localhost:5000处启动服务器. 在我的views.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.txt as

f = open('/static/english.txt')

它给出错误IOError: No such file or directory

如何访问此文件?

推荐答案

我认为问题是您将/放在了路径中.删除/,因为staticviews.py处于同一级别.

I think the issue is you put / in the path. Remove / because static is at the same level as views.py.

我建议将settings.py的级别设置为与views.py相同的级别,或者许多Flask用户更喜欢使用__init__.py,但我不这样做.

I suggest making a settings.py the same level as views.py Or many Flask users prefer to use __init__.py but I don't.

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.

这篇关于Flask:如何在应用程序根目录中读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆