New domain and blog

New domain and blog
Please head over to my new domain to view my blog and current projects

Monday, 22 April 2013

Route static files for BottlePy web framework

I have been using BottlePy on my Raspberry Pi for quite some time. I really like the simplicity of the framework and the ease at which you can get something up and running. The one issue I had, was that you could not load static css or js files. 

There are ways around this, like placing your files in Gist and linking to the raw code, but this can be an issue when you want to run your webserver 'offline'. The documentation is not very clear on how to do this, so here is what I did to get it working properly. 

This is the template that I use to route the static files. This is part of my main python code that runs the server.

# Routing static files
@get('/<filename:re:.*\.css>')
def stylesheets(filename):
return static_file(filename, root='static/css')
@get('/<filename:re:.*\.js>')
def javascripts(filename):
return static_file(filename, root='static/js')
@get('/<filename:re:.*\.(jpg|png|gif|ico)>')
def images(filename):
return static_file(filename, root='static/css/img')
Then all you need to do is add your file names in the .tpl file. By doing this, your css, or js files can be stored locally so they can still be served if you are offline. 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Raspberry Pi Test Page</title>
<link type="text/css" href="bootstrap.min.css" rel="stylesheet">
<link type="text/css" href="jquery-ui-1.10.2.custom.css" rel="stylesheet">
<script src="jquery-1.9.1.js"></script>
<script src="jquery-ui-1.10.2.custom.js"></script>
<script>
$(function()
{
$( "#dateFrom" ).datepicker();
$( "#dateTo" ).datepicker();
});
</script>
</head>
<body>
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li><a href="/home">Home Page</a></li>
<li><a href="/test">Test Page</a></li>
<li><a href="/testgraph">Test Graph</a></li>
<li><a href="/logout">Logout</a></li>
</ul>
</div>
</div>
<div class="container">
<h1>Page used for testing code and processes</h1>
<p>IP address is: {{ ipaddr }}</p>
<br/><br/><br/>
<form action="/test" method="get">
<div class="row-fluid">
<div class="span3">
<label>Date From</label>
<input type="text" id="dateFrom" name="from"/>
</div>
<div class="span3">
<label>Date to</label>
<input type="text" id="dateTo" name="to"/>
</div>
<div class="span3">
<input type="submit" class"btn" name="selectedDates" value="Submit Dates">
</div>
</div>
</form>
</div>
</body>
</html>
That is about it. I hope this helps because I really find this framework great to use and works flawlessly on my Raspberry Pi.

Greg

No comments:

Post a Comment