我的问题与本网站上的其他几个问题类似,但我发现那里的答案不适合我。
我正在学习 Flask。我在使用 Vagrant VM 的 Ubuntu 10.04 机器上运行 Flask 0.10.1 和 Python 2.7。
我尝试了无数来自 SO、Flask 文档和 Miguel Grinberg 的建议,但都没有成功。
所以我展示了我认为可以工作(但没有)供您细读的最简单的版本。
注释掉的替换行(在 page_a.html 和 page_b.html 中)确实有效但很丑陋。
首先,这是我的元素根目录下“tree”的输出:
这是文件(减去了 .html 中的一些样板文件)
page_a.html:
<head>
<link rel="stylesheet" href="styles.css">
<!-- <link rel="stylesheet" href="static/styles.css"> -->
</head>
<body>
<h1>page_a</h1>
<img src="an_image.png">
<!-- <img src="static/an_image.png"> -->
<a href="{{ url_for('page_b') }}">to page b</a>
</body>
page_b.html:
<head>
<link rel="stylesheet" href="styles.css">
<!-- <link rel="stylesheet" href="../../static/styles.css"> -->
</head>
<body>
<h1>page_b</h1>
<img src="../../static/an_image.png">
<!-- <img src="../../static/an_image.png"> -->
<a href="{{ url_for('page_a') }}">to page a</a>
</body>
初始化.py:
from flask import Flask
app = Flask('my_pages')
import my_pages.views
运行服务器.py:
from my_pages import app
app.run(host='0.0.0.0', port=5000, debug=True)
views.py:
from my_pages import app
from flask import render_template
@app.route('/')
@app.route('/page_a')
def page_a():
return render_template('page_a.html')
@app.route('/pages/page_b/')
def page_b():
return render_template('page_b.html')
样式.css:
body {
background-color: green;
}
当我在 page_a.html 和 page_b.html 中使用注释掉的行(而不是上面的行)时,此版本确实有效。
这是当我访问 page_a.html 时 runserver.py 的输出:
"GET /page_a HTTP/1.1" 200 -
"GET /styles.css HTTP/1.1" 404 -
"GET /an_image.png HTTP/1.1" 404 -
和 page_b.html。
"GET /pages/page_b/ HTTP/1.1" 200 -
"GET /pages/page_b/styles.css HTTP/1.1" 404 -
(最后显示我的“样式”目录中的“an_image.png”)
我的问题:我错过了什么?是否可以在不进行重大重构的情况下使此设置正常工作?
我当然不想硬编码每个静态文件的完整路径。
此外,在实际应用程序中,URL 运行在几个层次上——例如,
http://localhost:5000/book/<id_1>/chapter/<id_2>/page
非常感谢任何可能回复的人!
最佳答案
您并没有告诉 Flask 这些文件在您的静态文件夹中。最简单的方法是使用 url_for
。
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
关于python - Flask 在我的包的 'static' 目录中找不到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35593283/