如何从 Flask 中的子模块提供静态文件

问题描述 投票:0回答:1

我正在编写一个分为多个模块的 Flask 应用程序,每个模块都位于一个单独的文件夹中,其中包括“模板”和“静态”文件夹。

在每个模块中,我将全局变量“custom_js”传递给模板:

module_bp = Blueprint('module', __name__, template_folder='templates', static_folder='static')

# pass custom js files to the base template
@module_bp.context_processor
def custom_js_context():
    return {'custom_js': ['some_file.js']}

我将这些 JavaScript 文件包含在主模板 base.html 中,如下所示:

{% if custom_js %}
    {% for js_file in custom_js %}
        <script src="{{ url_for('static', filename='js/' + js_file) }}"></script>
    {% endfor %}
{% endif %}

上面的代码会添加到base.html。物理文件位于 /module/static/js/some_file.js,但访问 http://127.0.0.1:8080/static/js/some_file.js 会导致 404 错误。

如何从模块正确地提供这些 JavaScript 文件?


一个想法是将蓝图修改为:

module_bp = Blueprint('module', 
                         __name__, 
                         template_folder='templates', 
                         static_folder='static',
                         static_url_path='/module/static'
                         )

并将文件提供给模板,如下所示:

@module_bp.context_processor
def custom_js_context():
    custom_js_files = ['some_file.js']
    custom_js_with_prefix = ['/module/static/js' + filename for filename in custom_js_files]
    return {'custom_js': custom_js_with_prefix}

更新了base.html循环

{% if custom_js %}
    {% for js_file in custom_js %}
        <script src="{{ js_file) }}"></script>
    {% endfor %}
{% endif %}

但是,我不确定这在多大程度上是正确的方法。

python flask jinja2 static-files
1个回答
0
投票

这就是我解决这个问题的方法(这是否是 Flask 的普通方法,我不知道):

    _controller_name_ = "bugsandfeatures"
    _url_prefix_ = '/' + _controller_name_

    bp = Blueprint("bugsandfeatues", __name__,
                   template_folder='templates',
                   `enter code here`static_folder="static",
                   url_prefix=_url_prefix_)

注意 url_prefix,它确保蓝图实际上从其自己的路径提供静态文件(请参阅 [https://flask.palletsprojects.com/en/3.0.x/blueprints/#static-files][1])。

现在您可以:

    @bp.context_processor
    def custom_js_context():
        return {'custom_js': url_for('.static', filename='my_file.js')}

注意“。”前面有静电。它确保端点由当前蓝图解析。 当您在模板中选择变量时,您会得到“/bugsandfeatures/static/my_file.js”。 [1]:https://flask.palletsprojects.com/en/3.0.x/blueprints/#static-files

© www.soinside.com 2019 - 2024. All rights reserved.