我有一个包含模板和静态文件的 Flask 蓝图。模板呈现正确,但链接的 CSS 文件返回 404 未找到。如何提供位于蓝图文件夹下的静态文件?
app/
__init__.py
auth/
__init__.py
static/
style.css
templates/
index.html
auth = Blueprint('auth', __name__, template_folder='templates')
@auth.route('/')
def index():
return render_template('index.html')
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
最佳答案
通过传递 static_folder
告诉蓝图它的静态文件夹在哪里,然后使用 url_for
生成蓝图上 static
路由的 url。 This is described in the docs.
auth = Blueprint('auth', __name__, template_folder='templates', static_folder='static')
url_for('auth.static', filename='style.css')
此解决方案仅在蓝图具有 url_prefix
时有效。根据文档:
However, if the blueprint does not have a url_prefix, it is not possible to access the blueprint’s static folder. This is because the URL would be /static in this case, and the application’s /static route takes precedence. Unlike template folders, blueprint static folders are not searched if the file does not exist in the application static folder.
在这种情况下,一种解决方案可能是将样式表放入主 static
目录。
关于python - 提供位于 Flask 蓝图文件夹下的静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41484453/