从flask restful endpoint中的另一个目录提供静态html文件

Sal*_*ali 4 python flask

我有一个玩具REST应用程序,其结构如下:

 - client/
   - css/
   - js/
   - index.html
 - server/
   - app.py
   ... some other files  which I use in app.py
Run Code Online (Sandbox Code Playgroud)

app.py 是一个烧瓶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():
    ...
Run Code Online (Sandbox Code Playgroud)

现在我想提供我的静态索引html.所以看了这个,这个这个,我想我可以通过添加以下几行轻松地提供它:

@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'))
Run Code Online (Sandbox Code Playgroud)

我看不到我的html文件(日志告诉我:) 127.0.0.1 - - [some day] "GET / HTTP/1.1" 404 -.我知道我可以在服务器文件夹中移动index.html但是有没有办法从现在的位置提供服务?

PS当我添加app._static_folder = "../client/"并更改我的home函数时,return app.send_static_file('index.html')我终于开始接收我的html文件,但是html中的所有css/js文件都返回404.

sju*_*dǝʊ 8

创建flask应用程序时,将static_folder配置为客户端文件夹.

from flask import Flask
app = Flask(__name__, static_folder="client")
Run Code Online (Sandbox Code Playgroud)

然后你可以访问url上的js和css http://localhost:5000/static/css/main.css

关于你的初步问题.您可以像这样使用烧瓶提供静态html页面:

@app.route('/<path:path>')
def serve_page(path):
    return send_from_directory('client', path)
Run Code Online (Sandbox Code Playgroud)

  • 或者`app = Flask(__ name __,static_folder ='static',static_url_path ='')`如果你想避免url中的'static'. (5认同)