【问题标题】:Serve static files located under Flask blueprint folder提供位于 Flask 蓝图文件夹下的静态文件
【发布时间】:2017-05-19 23:05:18
【问题描述】:

我有一个包含模板和静态文件的 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') }}">

【问题讨论】:

    标签: python flask


    【解决方案1】:

    通过传递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 时才有效。根据文档:

    但是,如果蓝图没有 url_prefix,则无法访问蓝图的静态文件夹。这是因为在这种情况下 URL 将是 /static,并且应用程序的 /static 路由优先。与模板文件夹不同,如果文件在应用程序静态文件夹中不存在,则不会搜索蓝图静态文件夹。

    在这种情况下,一种解决方案可能是将样式表放入主 static 目录中。

    【讨论】:

      猜你喜欢
      • 2014-06-06
      • 1970-01-01
      • 2019-09-19
      • 2021-05-03
      • 2020-05-10
      • 2022-01-03
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      相关资源
      最近更新 更多