【问题标题】:Flask raises 404 for blueprint static files when using blueprint static route使用蓝图静态路由时,Flask 为蓝图静态文件引发 404
【发布时间】:2017-01-25 13:55:19
【问题描述】:

我的 Flask 应用程序上有一个蓝图 home,前缀为 /。蓝图有一个静态文件夹,并使用 static_folder 参数进行配置。但是,链接到蓝图的静态文件会返回 404 错误,即使该文件存在并且 url 看起来正确。为什么蓝图不提供静态文件?

myproject/
    run.py
    myapp/
        __init__.py
        home/
            __init__.py
            templates/
                index.html
            static/
                css/
                    style.css

myapp/init.py:

from flask import Flask

application = Flask(__name__)

from myproject.home.controllers import home

application.register_blueprint(home, url_prefix='/')

myapp/home/controllers.py:

from flask import Blueprint, render_template

home = Blueprint('home', __name__, template_folder='templates', static_folder='static')

@home.route('/')
def index():
    return render_template('index.html')

myapp/home/templates/index.html:

<head>
<link rel="stylesheet" href="{{url_for('home.static', filename='css/style.css')}}">
</head>
<body>
</body>

myapp/home/static/css/style.css:

body {
    background-color: green;
}

【问题讨论】:

  • 也许您应该将您的蓝图移动到 init.py 文件中?
  • 没有错误,只是一个白页。 body标签没有任何css样式,看不到背景。
  • 这是我上一个问题对我项目的更多辩护:stackoverflow.com/questions/41828711/…

标签: python flask


【解决方案1】:

您正在与 Flask 静态文件夹和您的蓝图发生冲突。由于蓝图挂载在/,它与应用共享相同的静态url,但应用的路由优先。更改蓝图的静态 url,使其不会冲突。

home = Blueprint(
    'home', __name__,
    template_folder='templates',
    static_folder='static',
    static_url_path='/home-static'
)

【讨论】:

  • 我做到了,现在面临这个错误werkzeug.routing.BuildError: Could not build url for endpoint 'static' with values ['filename']. Did you mean 'home.static' instead?
  • 我看到了问题,把你的url_prefix='/'改成url_prefix=''__init__.py
  • 我做了,但仍然是同样的错误。是否返回&lt;link rel="stylesheet" href="{{url_for('home.static', filename='css/style.css')}}"&gt; 行?
  • 之前你说你没有收到错误,现在它得到了这个?我有你完整的项目设置(基于你的另一个问题),这对我来说是 100% 的。
  • 你确定你输入了正确的代码吗?如果您的文件名= 在错误的位置,或者它丢失了,则会出现此错误。
【解决方案2】:

最后根据朋友的回答,我自己找到了正确的答案。 唯一的变化应该是这样的:

myapp/init.py:

application = Flask(__name__, static_folder=None)

myapp/home/controllers.py:

home = Blueprint('home', __name__, template_folder='templates', static_folder='static', static_url_path='static')

myapp/home/templates/index.html:

    <link rel="stylesheet" href="{{url_for('home.static', filename='style.css')}}">

【讨论】:

  • 这很有帮助,尽管对我来说,我将我的公共蓝图设置为:static_folder='../static', static_url_path='/static',在我的主应用程序调用中没有任何内容。然后我能够成功地将其引用为src="{{ url_for('public.static', filename='img/......
猜你喜欢
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 2014-06-06
  • 2017-05-19
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多