【问题标题】:Python Flask serving static files from root static folder rather than blueprint's static folderPython Flask 从根静态文件夹而不是蓝图的静态文件夹提供静态文件
【发布时间】:2014-06-06 02:54:25
【问题描述】:

我有一个蓝图定义为:

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

我将其注册为:

app.register_blueprint(auth_login, url_prefix='/user')

我有一条路线:

@auth_login.route('/<username>/')
def profile(username):
return render_template('profile/user.html',
username = username)

使用此设置,/user/ 端点永远无法加载静态文件,

“GET /user//static/css/lib/bootstrap.min.css HTTP/1.1” 404 - “GET /user//static/css/lib/font-awesome/css/font-awesome.min.css HTTP/1.1”404 -

我真正想要的是查看根应用程序的静态文件夹而不是蓝图,所以我希望它请求

“GET /static/css/lib/bootstrap.min.css HTTP/1.1”200 -

是否可以通过 static_folder 或 static_url_path 进行配置,以便路由将在根目录而不是相对于蓝图的安装位置查找静态文件?

【问题讨论】:

    标签: python flask


    【解决方案1】:

    默认情况下,Flask 设置/static URL 以提供来自{application_root}/static 的文件 - 您正在覆盖蓝图代码的默认设置。 (URL 仍然是 /static,但文件夹是 {application_root}/path/to/blueprint/static,从事物的声音来看,这不是您想要的)。

    只需 删除 static_folderstatic_url 参数到您的 Blueprint 初始化和 URL 应该可以正常工作(假设您的 {application_root}/static 文件夹中有适当的 CSS。)

    【讨论】:

    • 您好,感谢您的回复。我尝试删除 static_folder 和 static_url_path 变量,但它仍在向“GET /user//static/css/lib/bootstrap.min.css HTTP/1.1”404 发出请求 - 而不是 /static/css/ lib/bootstrap.min.css,好像没有什么区别。我的整个应用程序仓库中只有一个静态文件夹,那就是应用程序的静态文件夹。蓝图代码与静态文件夹处于同一级别。
    • @AviDas - 确保您至少为静态引用使用绝对路径 URL:&lt;link href="static/css/some.css&gt; 是相对路径,而 &lt;link href="/static/css/some.css&gt; 是绝对路径(注意前面的 / )。更好的是,使用{{ url_for('static', filename='/your/file.name') }},因此如果您将应用程序安装在不是 URL 根目录的位置,那么一切都将正常工作
    • @SienVieira 这就是问题所在,我会接受你的回答!只是好奇,我在哪里可以找到这种行为的文档?
    • @AviDas - 您需要查看RFC 3968 Section 5 以了解有关相对 URL 解析的规则。它的基本原理是相对 URL 不提供的所有内容都由其所在的上下文提供,如果路径是相对的,则合并路径,如果绝对路径则单独使用,并且相对部分之后的所有内容都按原样使用。
    猜你喜欢
    • 2019-09-19
    • 2017-05-19
    • 2021-05-03
    • 2023-03-06
    • 2020-05-10
    • 2016-01-06
    • 2017-08-25
    • 2020-08-08
    • 2022-01-03
    相关资源
    最近更新 更多