我的问题与该网站上的其他几个问题类似,但我找到的答案对我不起作用。
我正在学习 Flask。我正在使用 Vagrant VM 在 Ubuntu 10.04 计算机上运行 Flask 0.10.1 和 Python 2.7。
我尝试了 SO、Flask 文档和 Miguel Grinberg 的无数建议,但没有成功。
所以我展示了我认为的最简单的版本could为您的阅读工作(但不)。
注释掉的替换行(在 page_a.html 和 page_b.html 中)do工作但很丑陋。
首先,这是我的项目根目录上“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>
init.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)
视图.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;
}
这个版本does当我在 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 -
(最后显示了我的“styles”目录中的“an_image.png”)
我的问题: 我错过了什么?这个设置可以在不进行重大重构的情况下工作吗?
我当然不想硬编码每个静态文件的完整路径。
此外,在实际应用程序中,URL 运行多个层次——例如,
http://localhost:5000/book/<id_1>/chapter/<id_2>/page
非常感谢任何可能回复的人!