python - 从 flask restful 端点的另一个目录提供静态 html 文件

标签 python flask

我有一个玩具 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之后, thisthis ,我认为我可以通过添加以下行轻松地提供服务:

@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/

相关文章:

python - 操作 numpy 数组

python - Google Cloud Storage create_upload_url -- App Engine 灵活的 Python

python - sqlalchemy:TypeError:无法散列的类型创建实例,sqlalchemy

javascript - 在 Flask Web 应用程序中加载页面,同时使用 selenium 抓取另一个网站

python - 404 尝试链接到另一个页面 Flask 时出错

python - 使用 flask_ldap3_login 使用 LDAP 进行 Flask 身份验证

python - 使用json获取所有 "viewer"和 "timestamp"

python - 在 App Engine 中查询随时间变化的百分比

python - SSL - 为 Python 请求调用创建 client.crt 和 client.key

python - 覆盖类变量和并发 Flask 请求