在网络(Flask)应用程序中使用 os.getcwd() 是否可移植?

问题描述 投票:0回答:3

templates/index.html
文件中我可以写入

<link rel="stylesheet" type="text/css"
      href={{ url_for('static', filename='css/main.css') }}>

url_for
从静态文件夹中检索 CSS 文件就可以了(FWIW,尽管
css/main.css
在 Windows 上有一个正斜杠)。

我想打开一个静态文件

static/number.txt
,从中读取一个数字,然后显示该数字。

app.py

from flask import Flask, render_template, url_for


app = Flask(__name__)


@app.route('/')
def number():
    filename = url_for('static', filename='txt/number.txt')
    with open(filename) as f:
        number = next(f)
    return render_template('index.html', number=number)


if __name__ == '__main__':
    app.run()

静态/txt/number.txt

2345

模板/index.html

<body>
    {{ number }}
</body>

对于这个简单的示例,我并没有尝试通过运行 Nginx 进行优化 而 IIUC 这个简单的任务不需要

send_from_directory()
也不是
os.getcwd()
。也无需修改
app.static_folder
,也无需担心使用
os.join.path()
的文件夹分隔符(我碰巧在 Windows 上,但理想情况下这应该在代码中不可见)。也不需要修改默认的
static
文件夹。

上面的代码给了我

c:\read-static>python app.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "C:\anaconda3\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  ...
  File "app.py", line 10, in number
    with open(filename) as f:
FileNotFoundError: [Errno 2] No such file or directory: '/static/txt/number.txt'
127.0.0.1 - "GET / HTTP/1.1" 500 -

我错过了什么?我应该使用

os.getcwd()
来读取 Flask 中的静态文件吗?依赖
os.getcwd()
的某些东西似乎令人难以接受/黑客。

flask
3个回答
0
投票

使用

import os

并将

url_for(...)
行替换为:

filename = os.path.join(os.getcwd(), 'static', 'txt', 'number.txt')

是一个解决方案。

但问题依然存在。使用

url_for(...)
不是完全可以吗?


0
投票

回答你的第二个问题:

“但问题是。使用 url_for(...) 不是完全可以吗?”

url_for(static, filename='bla.txt')
返回
/static/bla.txt
,而不是
static/bla.txt
。由于起始斜杠表示计算机的根目录,因此您尝试直接在 PC 的根目录(不存在)中打开静态文件夹。

我认为

url_for(static, filename='bla.txt')[1:]
应该可以工作,但我认为这是一个非常hacky的解决方案。

所以不,它的定义并不完全正确,我绝对不建议使用它。站点路由和文件夹结构不是一回事,如果没有充分的理由,不应将其混合在一起(这不是一个)。


0
投票

要设置完整路径,您不必在 python 中使用 url_for。

所以,我的建议是将代码更改为:

from os import path # os needed for folder and file address
# receiving address of a current directory 
script_dir = path.dirname(path.abspath(__file__))
# adding address of your file
filename = script_dir.join('/static/txt/number.txt')
© www.soinside.com 2019 - 2024. All rights reserved.