热线电话:13121318867

登录
2019-01-27 阅读量: 685
无法访问根地址的静态文件

使用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”调用资源,这次找到并加载文档。)

解决办法:想到的是你可能已经指定了website.com/static在WSGI服务器脚本中保存所有静态文件。因此,烧瓶应用程序不会干扰哪些请求website.com/static和WSGI服务器处理这些请求,而WSGI服务器无法在文件夹中找到它们。

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

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

0.0000
5
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子