【问题标题】:Flask import static resourcesFlask 导入静态资源
【发布时间】:2013-08-15 21:41:22
【问题描述】:

问题:当我从'/' 以外的任何路由访问静态资源时,我得到一个 404。

我的Flask 应用程序的static 文件夹中有一个名为volume.png 的图像。当我使用@app.route('/') 将我的主页路由到'/' 时,它发现图像很好,当我点击localhost:5000/static/images/volume.png 时我可以显示图像。但是当我使用任何其他链接时,例如'/s',它说在s/static/images/volume.png 中找不到图像。即使我创建了一个s 目录并将static 目录复制到其中,当我输入localhost:5000/s/static/images/volume.png 时,我也会得到一个404。我考虑过使用Flask-Assets,但似乎没有太多文档或示例。确保我的路由可以访问静态资源的好方法是什么?

【问题讨论】:

  • 你试过localhost:5000/s/../static/images/volume.png吗?在我看来,您正在传递一个相对路径到您的路线,而不是从您的项目根目录开始并从那里遍历。
  • 不,它会立即重定向到localhost:5000/s/static/images/volume.png 并给出404
  • 你一定要走这条路吗?可以重定向到 / 吗?
  • 是的,我能做到。为什么使用不同的路由和访问静态资源不简单?
  • 嗯,有一种方法可以使这变得简单,但它需要一些硬编码。一种解决方案是将/<path:resource> 变量添加到每个人的 URL 路由之一(或至少到您驾驶的每条路由)的末尾。所以 s 路由会变成 '/s/<path:resource>' 并且你会按照资源路径访问你的静态资源。

标签: flask flask-assets


【解决方案1】:

您需要在 HTML(或 CSS)中限定图片的路径:

<!-- This will break in the way you describe -->
<img src="static/images/volume.png" />

<!-- This will not -->
<img src="/static/images/volume.png" />

<!-- Nor will this (assuming you are using a Jinja template) -->
<img src="{{ url_for('static', filename='images/volume.png') }}" />

这是因为用户代理需要解析 URI 的相对路径(请参阅section 5.1 of RFC 3968 for the details)。

使用static/images/volume.png 会在/ 产生以下路径:

scheme://host.name/static/images/volume.png

以及以下/s:

scheme://host.name/s/static/images/volume.png

正如你所发现的。通过确保为资源提供绝对的path 组件(至少),您可以确保浏览器仅将您提供的路径与schemehost.name 合并,而不是与scheme、@987654332 @和path

【讨论】:

    猜你喜欢
    • 2018-09-17
    • 1970-01-01
    • 2021-08-23
    • 2021-05-16
    • 2022-12-04
    • 2013-08-01
    • 2014-08-29
    • 2014-07-29
    • 1970-01-01
    相关资源
    最近更新 更多