我有一个玩具 REST 应用程序,其结构如下:
- client/
- css/
- js/
- index.html
- server/
- app.py
... some other files which I use in app.py
app.py
是一个 flask 的 restful 端点,如下所示:
app = flask.Flask('some-name')
# a lot of API end points, which look in this way
@app.route('/api/something', methods=['GET'])
def func_1():
...
现在我想提供我的静态索引 html。所以看了this之后, this和 this ,我认为我可以通过添加以下行轻松地提供服务:
@app.route('/')
def home():
# but neither with this line
return app.send_static_file('../client/index.html')
# nor with this
return flask.render_template(flask.url_for('static', filename='../client/index.html'))
我看不到我的 html 文件(日志告诉我:127.0.0.1 - - [some day] "GET/HTTP/1.1"404 -
)。我知道我可以移动服务器文件夹中的 index.html,但有没有办法从现在的位置提供它?
P.S. 当我添加 app._static_folder = "../client/"
并将我的主页功能更改为 return app.send_static_file('index.html ')
我终于开始接收我的 html 文件,但是 html 中的所有 css/js 文件都返回 404。
最佳答案
创建 Flask 应用程序时,将 static_folder 配置到您的 client 文件夹。
from flask import Flask
app = Flask(__name__, static_folder="client")
然后就可以在url http://localhost:5000/static/css/main.css
上访问js和css了
关于您最初的问题。您可以像这样使用 flask 提供静态 html 页面:
@app.route('/<path:path>')
def serve_page(path):
return send_from_directory('client', path)
关于python - 从 flask restful 端点的另一个目录提供静态 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28951256/