【问题标题】:Flask - Can't access static files for root address [duplicate]Flask - 无法访问根地址的静态文件[重复]
【发布时间】:2019-01-26 23:01:28
【问题描述】:

我正在使用 Flask 为自己创建一个个人测试网站,但是我发现了一种我无法完全摆脱的行为,可能需要一些帮助。

我使用 Flask 的蓝图系统将我的网站分成了多个单独的块,因为这对我的案例有意义(因为我希望它包含多个较小的测试应用程序)。我怀疑我的问题根源于我的项目结构,所以我简要概述了我所做的事情。这是我的(简化的)项目设置:

>File structure:
root (contains some linux start scripts)
  - run.py
  - website (the actual flask project folder)
      - __init__.py (registers blueprints)
      - blueprints
          - __init__.py (empty)
          - website
              - __init__.py (defines routes, creates blueprint)
              - static (static files for this blueprint)
                  - css
                      - example.css
              - templates (render templates for this blueprint)
                  - example.html.j2
          - app1
              - <Same structure as above>
          - app2
              - <Same structure as above>
          - ...

>run.py
from website import createApp
createApp().run(debug=True)


>website/__init__.py:
from flask import Flask, render_template

def createApp():
    app = Flask(__name__)
    app.testing = True

    # Website
    from blueprints.website import website
    app.register_blueprint(website())
    # App1
    from blueprints.app1 import app1
    app.register_blueprint(app1())
    # App2
    from blueprints.app2 import app2
    app.register_blueprint(app2())
    ...
    return app


>website/blueprints/website/__init__.py:
from flask import Blueprint, render_template
bp = Blueprint("website", __name__, url_prefix="/", 
template_folder="templates", static_folder="static")
def website():
    return bp

@bp.route('/')
def index():
    return render_template('example.html.j2')


>website/blueprints/website/templates/example.html.j2
<html>
  <head>
    <link rel="stylesheet", href="{{url_for('website.static', filename='css/example.css')}}">
    <title>Test Page!</title>
  </head>
  <body>
    This is a test page!
  </body>
</html>

预期结果:页面应该以 example.css 中定义的样式显示
实际结果:加载 example.css 文档会导致 404 错误。

自从我尝试处理这个问题几个小时以来,我认为我已经将问题归结为 Flask 在根地址方面很奇怪。

由于蓝图将地址定义为url_prefix="/",我通过在浏览器中输入“website.com”来访问它。 (浏览器尝试通过“website.com/static/css/example.css”调用资源,但得到 404 响应。)

如果我将地址更改为url_prefix="/test" 并通过“website.com/test”访问该页面,样式表将成功加载。 (浏览器现在尝试通过“website.com/test/static/css/example.css”调用资源,这次找到并加载了文档。)

由于这应该是主页,但我确实希望它使用根地址。

如果有人能对此有所启发并向我解释我的错误所在,我将不胜感激。

【问题讨论】:

    标签: python flask jinja2 static-files blueprint


    【解决方案1】:

    有趣的问题。我唯一能想到的是,您可能已经指定website.com/static 将所有静态文件保存在您的 WSGI 服务器脚本中。因此,flask 应用程序不会干扰对website.com/static 的哪些请求,并且这些请求由在文件夹中找不到它们的 WSGI 服务器处理。

    使用开发服务器时是否也会出现这个问题?

    您可以尝试将 WSGI 设置中的静态服务器更改为 website/blueprints/static/website 文件夹吗?

    最后,如果这没有帮助,你能用这个问题做一个小的 github repo 吗?使用这些类型的导入和文件树很难重现这个问题。

    【讨论】:

    • 环境已经是Flask开发服务器,运行在朋友的Linux服务器上。我从来没有研究过 WSGI,我需要一些时间来测试它,因为我需要做一些实验,我会得到结果。