I’ve started a new project with bottle.py and had some hiccups with static files and templates.
My project layout is (something) like that:
/ app.wsgi bottle.py static/ static/css static/css/bootstrap-theme.min.css static/css/bootstrap.min.css static/img static/img/logo.png static/js static/js/bootstrap.min.js static/js/npm.js static/js/tab.js static/js/jquery-1.12.1.min.js views/ views/search.tpl views/index.tpl views/header.tpl views/footer.tpl
my app.wsgi is looking something like (dynamic routes & templates):
@bottle.route('/') @bottle.route('/< action >/< name >') def main(action='/',name=None): if ( action == '/' ) : return template("index", title=" some title ") else: return template(action, title=" some title ", name=name) application = bottle.default_app()
I can translate every REST request to a new template and use AJAX inside the templates.
But what-about static files like stylesheets and javascripts ?
eg.
< script src="jquery-1.12.1.min.js"> < / script> < img src="logo_hp.png" >
When working with dynamic routes (or any routes in bottle) unless you are using the main app.wsgi everything else will be translated to something like:
GET /search/jquery-1.12.1.min.js GET /view/jquery-1.12.1.min.js etc
If you noticed the layout then somehow we need to map all static files (css,js,images) to our static folder. We can map static files from "/" with the code below:
@bottle.get('< filename:re:.*.js >') def static_js(filename): return static_file(filename, root='static/js') @bottle.get(' < filename:re:.*.css > ') def static_css(filename): return static_file(filename, root='static/css') @bottle.get(' < filename:re:.*.png > ') def static_img(filename): return static_file(filename, root='static/img')
Ok, that worked for the initial route (index page) but what about all the other templates & requests?
The solution was really (really) very very simply, even if it took me a couple hours to figure it out!!
I just needed to add a forward slash in front of every static file:
< script src="/jquery-1.12.1.min.js"> < / script> < img src="/logo.png" >
and the GET request becomes:
"GET /jquery-1.12.1.min.js
and we can now route the static files to our static file directory.