Python Notes and Examples

Web Development

Have a look at Django or Flask.

That said, for a really fast way to get started, Bottle is one file (bottle.py). You can download it and drop it into your project dir, or else install it via apt.

Bottle

To create a bottle webapp, start with:

mkdir my-webapp
cd my-webapp
wget http://bottlepy.org/bottle.py  # Directly gets the very latest bottle.
touch main.py
chmod +x main.py

Make main.py look like:

Run that (./main.py), then point your browser to http://localhost:8080/hello/world.

Pages served will not have any doctype, html, or head tags. We’ll get back to how to include those.

When you run the webapp, you’re in bottle.run(…) until you Ctrl-C to stop the webapp. bottle.run waits for requests, services them, and waits for the next request.

Bottle handles requests sequentially; the previous request must complete and return a response before the next one is looked at.

Bigger example

Notes about routing

Terminology: /<foo> is the route, index is the callback.

Bottle passes the value for the wildcard (here, whatever <foo> is) as a keyword arg to the callback.

Routes may or may not end with a trailing slash. Bottle pays attention, and considers them different routes.

Instead of @route, you can use @get or @post (or @put, @delete, @patch). @get(...) == @route(...), and @post == @route('...', method='POST').

If you want, you can bind more than one route to a callback:

You can use a “filtered” wildcard like so:

@bottle.route('/id-num/<id_num:int>')
def show_by_id(id_num):
    # `id_num` is an int.