【发布时间】:2019-01-26 23:01:28
【问题描述】:
我正在使用 Flask 为自己创建一个个人测试网站,但是我发现了一种我无法完全摆脱的行为,可能需要一些帮助。
我使用 Flask 的蓝图系统将我的网站分成了多个单独的块,因为这对我的案例有意义(因为我希望它包含多个较小的测试应用程序)。我怀疑我的问题根源于我的项目结构,所以我简要概述了我所做的事情。这是我的(简化的)项目设置:
>File structure:
root (contains some linux start scripts)
- run.py
- website (the actual flask project folder)
- __init__.py (registers blueprints)
- blueprints
- __init__.py (empty)
- website
- __init__.py (defines routes, creates blueprint)
- static (static files for this blueprint)
- css
- example.css
- templates (render templates for this blueprint)
- example.html.j2
- app1
- <Same structure as above>
- app2
- <Same structure as above>
- ...
>run.py
from website import createApp
createApp().run(debug=True)
>website/__init__.py:
from flask import Flask, render_template
def createApp():
app = Flask(__name__)
app.testing = True
# Website
from blueprints.website import website
app.register_blueprint(website())
# App1
from blueprints.app1 import app1
app.register_blueprint(app1())
# App2
from blueprints.app2 import app2
app.register_blueprint(app2())
...
return app
>website/blueprints/website/__init__.py:
from flask import Blueprint, render_template
bp = Blueprint("website", __name__, url_prefix="/",
template_folder="templates", static_folder="static")
def website():
return bp
@bp.route('/')
def index():
return render_template('example.html.j2')
>website/blueprints/website/templates/example.html.j2
<html>
<head>
<link rel="stylesheet", href="{{url_for('website.static', filename='css/example.css')}}">
<title>Test Page!</title>
</head>
<body>
This is a test page!
</body>
</html>
预期结果:页面应该以 example.css 中定义的样式显示
实际结果:加载 example.css 文档会导致 404 错误。
自从我尝试处理这个问题几个小时以来,我认为我已经将问题归结为 Flask 在根地址方面很奇怪。
由于蓝图将地址定义为url_prefix="/",我通过在浏览器中输入“website.com”来访问它。 (浏览器尝试通过“website.com/static/css/example.css”调用资源,但得到 404 响应。)
如果我将地址更改为url_prefix="/test" 并通过“website.com/test”访问该页面,样式表将成功加载。 (浏览器现在尝试通过“website.com/test/static/css/example.css”调用资源,这次找到并加载了文档。)
由于这应该是主页,但我确实希望它使用根地址。
如果有人能对此有所启发并向我解释我的错误所在,我将不胜感激。
【问题讨论】:
标签: python flask jinja2 static-files blueprint