Flask蓝图静态目录不起作用?
根据Flask的说明,蓝图的静态文件应该可以通过 blueprintname/static
访问。但是出了一些问题,它并没有正常工作。
我的蓝图结构是这样的:
app/frontend/views.py
:frontend = Blueprint('frontend', __name__, template_folder='templates', static_folder='static') @frontend.route('/') etc...
app/frontend/js/app.js
: 我的JavaScript代码- 蓝图已经在Flask应用中注册(路由正常工作,一切都好)
当我访问 abc.com/frontend/static/js/app.js
时,它却返回了404错误。
我按照Flask的说明去获取我的静态文件:
<script src="{{url_for('frontend.static', filename='js/app.js')}}"></script>
输出结果是
<script src="/static/js/app.js"></script>
但这也不行。我的根目录 app/static/
文件夹里什么都没有。
我无法访问蓝图中的任何静态文件!Flask的说明说应该可以访问的!
admin = Blueprint('admin', __name__, static_folder='static')
默认情况下,路径的最右边部分是它在网上的可访问位置。因为这个文件夹叫做static,所以它会在蓝图的位置 + /static下可用。比如说,如果蓝图注册在/admin,那么静态文件夹就会在/admin/static。
6 个回答
我来得有点晚,不过之前的回答对我实现需求并没有太大帮助。我发现我需要做一些“技巧”才能让模块的静态文件夹按我想要的方式工作。我的应用程序由几个模块组成,但现在先假装我们有一个“application”作为主应用文件夹,还有一个“locations”作为模块文件夹,里面放着一个本地的“static”目录(我们需要从这个模块加载静态文件)。以下是我所做的步骤:
- 在主应用的
__init__.py
文件中,我给我的蓝图定义添加了url_prefix='/'
- 在模块的
routes.py
文件中,我使用了两个静态参数:static_folder='static'
和static_url_path='/locations/static'
来声明蓝图 - 在 HTML 模板中(这个模板是从主应用文件夹中的一个模板扩展而来的),我用以下代码来获取静态 CSS 文件的路径:
{{url_for('locations_bp.static', filename='css/style.css')}}
(locations_bp
是我为“locations”模块定义的蓝图名称)
这样,CSS 文件的加载路径就是 /locations/static/css/style.css
,这正是我想要实现的:最重要的是,我使用的 url_prefix 让我避免在所有模块的路由上加前缀。
我正在使用Flask的蓝图功能。
我的网页应用 考勤管理器 有三种用户类型:管理员、老师和学生。
下面是文件结构的一部分:
+---app.py
|
|
+---student
| | student.py
| | __init__.py
| |
| +---static
| | +---css
| | | login-page.css
| | | signup-page.css
| | |
| | \---js
| | firebaseConfig.js
| |
| +---templates
| | base.html
| | student-login-page.html
| | student-signup-page.html
app.py:
app.register_blueprint(student, url_prefix='/student')
student.py:
student = Blueprint('student', __name__, static_folder='static', template_folder='templates')
student-login-page.html:
<link rel="stylesheet" type="text/css" href="{{ url_for('student.static', filename='css/login-page.css') }}">
在student-login-page.html中,把'the_name_of_the_blueprint.static'加到url_for()的第一个参数里(或者在你链接CSS的地方)帮我解决了问题。
我在官方文档中找到了这个解决方案 这里。
如果这个方法没有解决你的问题,可以参考这个 GitHub问题或者这个 Reddit帖子,可能会对你有帮助。
祝你好运!
我这样初始化蓝图就成功了:
configuration = Blueprint('configuration', __name__, template_folder='templates',static_folder='static')
然后像这样引用静态文件:
href="{{ url_for('.static', filename='css/base.css') }}"
注意在 href 前面有一个点。
你可能把你的蓝图(Blueprint)注册到了你网站的根目录:
app.register_blueprint(core, url_prefix='')
但是蓝图中的 static
视图和你其他的蓝图视图没有什么不同;它使用 url_prefix
的值来让网址变得独特。
核心的 static
视图也是活跃的,所以现在有两个路径都想处理 /static/
的网址。如果你在注册蓝图的时候没有设置网址前缀,你就得给这两个路径中的一个设置一个独特的路径。
你可以给蓝图设置一个自定义的 static_url_path
值,或者使用核心 Flask 的 app
。
我在静态路径参数(static_url_path)中加入了一个参数,这样可以确保蓝图的静态路径不会和主应用的静态路径冲突。
比如:
admin = Blueprint('admin', __name__, static_folder='static', static_url_path='/static/admin')