Daily Archives:October 25th, 2014

Experimenting with Bower and Flask

This is another of those “just in case you’re Googling for it” posts…

Background:

  • Flask is a nice lightweight Python web framework – a handy way to create small web apps when you don’t need the power of something like Django.
  • Bower is a package manager for web components – a really easy way to get the latest versions of jQuery, bootstrap and anything else you might want.

Bower will put the packages into a folder called bower_components, with the idea that your deployment process will use something like Grunt to move the static bits from there into their final location. This is all well and good, but it seems like overkill if you’re just experimenting on your own machine.

Wouldn’t it be nice if Bower could just put the packages somewhere that they could be served directly as static files by Flask?

Well, it turns out that it can. If you create a file in the top level of your app called .bowerrc containing the following:

{
   "directory" : "static/bower_components"
}

then Bower will put its components in a subdirectory of the static folder and Flask then knows how to serve them up. You might do:

bower install jquery
bower install bootstrap

and then in your HTML you could use something like the following:

<link rel="stylesheet"
    href="/static/bower_components/bootstrap/dist/css/bootstrap.min.css" />

and for the Javascript:

<script src="/static/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/static/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>

You could leave out the bower_components bit at each stage and make your URLs even tidier, but I felt it was still useful to separate those bits that were being managed by Bower from those that weren’t.

Hope that helps someone!

© Copyright Quentin Stafford-Fraser