Bottle--A Python Web Micro Framework

I was looking for, at the moment, an answer to a question about a minimalist framework for doing a web site and have been surprised. I have used Karrigell a couple of times and was pleased. It is easy to figure out and doesn't get in your way. The word micro doesn't come to mind but it would be a possibility.

I did a bit more looking and found a couple of very interesting options, web.py and Bottle. While they both qualify as micro, Bottle just had a lot more appeal. Here are a few reasons:

  • The whole distribution is one python file of 3197 lines including a WSGI web server.
  • It can be up and running with no configuration.
  • It works (with no changes or configuration) in Python 2.5+ or Python 3.
  • I particularly like the way you handle URLs (which I will explain a bit more below).

To talk a bit more about it, we need some code. Here is a fancy version of "Hello world" using bottle:

from bottle import route, run
@route('/')
@route('/hello/')
def index(name='world'):
      return '<b>Hello %s!</b>' % name

run(host='localhost', port=9999)
As you might expect, to run it, you just feed it to the Python interpreter. I called it bt.py so the command python bt.py will do it.

Now, the fancy thing is that if you browse to http://localhost:9999 the output will be "Hello world!" but if you browse to http://localhost:9999/hello/Harry it prints "Hello Harry!". As you might expect, http://localhost:9999/hello (and lots of other URLs) will give you a 404 error.

The route decorators are what does the heavy lifting. Besides these basic uses, you can add what are called filters to be more creative. Filter choices include some basics such as only matching an integer but, if you want to get fancy, they can include regular expressions.

Beyond these basics, bottle includes a templating engine, some plugins and some adpaters to make it work with an assortment of production-grade web interfaces when you get beyond the capabilities of the built-in server.

That's enough to give you an idea of what bottle is/can do and more than enough to answer the question that got this started.

Tags: