我想让 flask 为我的静态目录中的所有文件夹提供 index.html。 tree 显示如下:
static/
├── contact
│ └── index.html
├── index.html
└── notoken
└── index.html
我希望 /notoken 或 /contact 显示 /notoken/index.html 和 /contact/index.html 中的内容。 html。 P.S:我不想使用 render_template 或 send_from_directory 或类似的东西为他们提供服务,因为我不想为每个文件/文件夹都这样做
请您参考如下方法:
编写一个捕获路径的 View 。在该路径下提供 index.html 文件。不存在的路径将返回 404。
@app.route('/pages/')
@app.route('/pages/<path:path>')
def page(path=''):
html = os.path.join(path, 'index.html')
return app.send_static_file(html)
使用 url_for 生成 url。不过,您只能在模板中调用它,而不能在静态文件中调用。
url_for('page', path='contact')
# /page/contact
添加page前缀是为了区别于其他url,否则可能会发生冲突,因为path本质上是通配符匹配。
