使用蓝图静态路由时,Flask为蓝图静态文件引发404

时间:2017-01-25 13:55:19

标签: python flask

我的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;
}

2 个答案:

答案 0 :(得分:6)

您与Flask静态文件夹和蓝图发生冲突。由于蓝图安装在/,因此它与应用程序共享相同的静态URL,但应用程序的路径优先。更改蓝图的静态URL,使其不会发生冲突。

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

答案 1 :(得分:2)

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

的myapp / init.py:

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

的myapp /家/ controllers.py:

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

的myapp /家/模板/ index.html中:

sbt debian:packageBin
相关问题