Flask Blueprint 找不到静态文件夹

9 投票
4 回答
7854 浏览
提问于 2025-04-21 04:38

我在我的Flask应用中设置了一个Blueprint(蓝图),但是我发现我的静态文件夹一直无法正常工作。每次尝试访问这些文件时,我都收到了404错误:

127.0.0.1 - - [11/Sep/2014 15:14:20] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 -
127.0.0.1 - - [11/Sep/2014 15:14:20] "GET /static/static/css/bootstrap.min.css HTTP/1.1" 404 -

而且CSS文件的路径还多加了一个“static”。JS文件的路径是正确的(/static),但似乎也无法正常工作。目前,我的静态文件夹放在蓝图的根路径下(app/dashboard)。我尝试把它放到app/static,但错误依然如故。

我现在的设置是这样的:

app/dashboard/__init__.py

from flask import Blueprint
dashboard = Blueprint('dashboard', __name__, template_folder='templates', static_folder='static')
from application.dashboard import controllers

app/__init__.py

# Blueprints      
from flask import Blueprint
from application.dashboard import dashboard
app.register_blueprint(dashboard)

app/templates/layout.html中,我有一行代码引用了两个静态文件,如下所示:

<link rel="stylesheet" type="text/css" href="{{ url_for('dashboard.static', filename='css/bootstrap.min.css') }}">
<script src="{{ url_for('dashboard.static', filename='js/bootstrap.min.js') }}"></script>

我的app/dashboard/static目录:

$ tree application/dashboard/static/
application/dashboard/static/
├── css
│   ├── bootstrap-theme.css
│   ├── bootstrap-theme.css.map
│   ├── bootstrap-theme.min.css
│   ├── bootstrap.css
│   ├── bootstrap.css.map
│   └── bootstrap.min.css
├── fonts
│   ├── glyphicons-halflings-regular.eot
│   ├── glyphicons-halflings-regular.svg
│   ├── glyphicons-halflings-regular.ttf
│   └── glyphicons-halflings-regular.woff
└── js
    ├── bootstrap.js
    └── bootstrap.min.js

有没有人知道这是怎么回事?我该如何正确地组织我的Blueprint?我按照Flask文档上的说明操作,但还是遇到了这个错误。

谢谢。

4 个回答

-1

为什么不使用nginx呢?因为它在性能上更快,而且你不需要写代码就能提供静态内容。

1

我也遇到过同样的问题。解决办法是去找到 __init__.py 这个文件,它是用来定义蓝图的,然后在定义蓝图的语句里加上 static_folder="static"

from flask import Blueprint

main = Blueprint('main', __name__ ,static_folder = "static")

from . import routes

因为 app 实际上是作为 Blueprint 运行的,这里是 main,所以这条指令告诉它去主包里找静态文件夹。如果你把这个加到 __init__.py 的应用脚本里是没用的(问我怎么知道的……)

1

你需要为你的蓝图添加一个网址前缀,像这样

app.register_blueprint(dashboard, url_prefix='/dashboard')
12

看起来你在应用程序和蓝图中有两个相同的路由,这可能会导致问题。你可以看看我在另一个回答的第三部分

你的应用程序路由 /static/<path:path> 指向 .static 这个端点。

而你的蓝图路由 /static/<path:path> 指向 dashboard.static 这个端点,因为在注册蓝图时你没有设置 url_prefix,所以它默认使用了 /static 作为静态文件夹的前缀。

所以你可以尝试以下几种解决方案:

  1. 只使用应用程序的静态文件夹。
  2. 在注册蓝图时设置 url_prefix
  3. 为蓝图使用另一个静态文件夹前缀。
  4. 禁用应用程序的静态文件夹,代码是 app = Flask(__name__, static_folder=None)
  5. 使用静态端点描述符的技巧

撰写回答