首选方法是使用Nginx或其他Web服务器提供静态文件。他们将比Flask更有效率。
但是,你可以用来send_from_directory从目录发送文件,这在某些情况下非常方便:
from flask import Flask, request, send_from_directory
# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')
@app.route('/js/<path:path>')
def send_js(path):
return send_from_directory('js', path)
if __name__ == "__main__":
app.run()
千万不能使用send_file或send_static_file与用户提供的路径。
send_static_file 例:
from flask import Flask, request
# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')
@app.route('/')
def root():
return app.send_static_file('index.html')