用flask加载静态html模板,并解决路由要加static的问题

来源:互联网 发布:数据库是什么意思 编辑:程序博客网 时间:2024/04/29 19:25

最近在学习flask,想建一个个人主页,看到一个博主写的处理static路由的问题。

Flask对Jinja2模版引擎支持很好,但无奈其所有静态文件都要放在static文件夹中(URL路由得加/static/...)而修改模版对于我这种前端0基础的开发又是个体力活

Flask官网好像没有找到类似的例子,于是Google解决方案,找到这篇博文:
https://vilimpoc.org/blog/2012/11/21/serving-static-files-from-root-and-not-static-using-flask/

博主说实例化Flask类的时候做一个小设置static_url_path=''即可,把static_url_path设置为空字符串相当于设置把所有根目录下URL的访问都关联到/static/目录下,所以静态HTML模版中直接可以引用/js/something.js而不是/static/js/something.js这样麻烦咯

虽然他们实际上还是存放在/static/目录下,只是修改了映射关系

顺带推荐一个HTML5优质模版网站(全免费):http://html5up.net/


That’all,最后放上我完整的py文件(超简单):

from flask import Flaskapp = Flask(__name__,static_url_path='',root_path='/home/ronny/mywebsite')    #静态模板index.html等都放在‘/home/ronny/mywebsite/static/'下。 路由不用再加’/static/index.html‘而是'index.html'就好@app.route('/')def index():    return app.send_static_file('index.html')if __name__ == '__main__':    app.run(host='0.0.0.0',port=8081,debug=True)   #真正运行时不要用debug=True
0 0
原创粉丝点击