Tutorial¶

This tutorial introduces you to the concepts and features of the Bottle web framework and covers basic and advanced topics alike. You can read it from start to end, or use it as a reference later on. The automatically generated API Reference may be interesting for you, too. It covers more details, but explains less than this tutorial. Solutions for the most common questions can be found in our Recipes collection or on the Frequently Asked Questions page. If you need any help, join our mailing list or visit us in our IRC channel.

Installation¶

Bottle does not depend on any external libraries. You can just download bottle.py into your project directory and start coding:

$ wget bottlepy.org/bottle.py

This will get you the latest development snapshot that includes all the new features. If you prefer a more stable environment, you should stick with the stable releases. These are available on PyPI and can be installed via pip (recommended), easy_install or your package manager:

$ sudo pip install bottle              # recommended
$ sudo easy_install bottle             # alternative without pip
$ sudo apt-get install python-bottle   # works for debian, ubuntu, ...

Either way, you’ll need Python 2.5 or newer (including 3.x) to run bottle applications. If you do not have permissions to install packages system-wide or simply don’t want to, create a virtualenv first:

$ virtualenv develop              # Create virtual environment
$ source develop/bin/activate     # Change default python to virtual one
(develop)$ pip install -U bottle  # Install bottle to virtual environment

Or, if virtualenv is not installed on your system:

$ wget https://raw.github.com/pypa/virtualenv/master/virtualenv.py
$ python virtualenv.py develop    # Create virtual environment
$ source develop/bin/activate     # Change default python to virtual one
(develop)$ pip install -U bottle  # Install bottle to virtual environment

Quickstart: “Hello World”¶

This tutorial assumes you have Bottle either installed or copied into your project directory. Let’s start with a very basic “Hello World” example:

from bottle import route, run

@route('/hello')
def hello():
    return "Hello World!"

run(host='localhost', port=8080, debug=True)

This is it. Run this script, visit localhost:8080/hello and you will see “Hello World!” in your browser. Here is how it works:

The route() decorator binds a piece of code to an URL path. In this case, we link the /hello path to the hello() function. This is called a route (hence the decorator name) and is the most important concept of this framework. You can define as many routes as you want. Whenever a browser requests an URL, the associated function is called and the return value is sent back to the browser. Its as simple as that.

The run() call in the last line starts a built-in development server. It runs on localhost port 8080 and serves requests until you hit Control-c. You can switch the server backend later, but for now a development server is all we need. It requires no setup at all and is an incredibly painless way to get your application up and running for local tests.

The Debug Mode is very helpful during early development, but should be switched off for public applications. Keep that in mind.

Of course this is a very simple example, but it shows the basic concept of how applications are built with Bottle. Continue reading and you’ll see what else is possible.

The Default Application¶

For the sake of simplicity, most examples in this tutorial use a module-level route() decorator to define routes. This adds routes to a global “default application”, an instance of Bottle that is automatically created the first time you call route(). Several other module-level decorators and functions relate to this default application, but if you prefer a more object oriented approach and don’t mind the extra typing, you can create a separate application object and use that instead of the global one:

from bottle import Bottle, run

app = Bottle()

@app.route('/hello')
def hello():
    return "Hello World!"

run(app, host='localhost', port=8080)

The object-oriented approach is further described in the Default Application section. Just keep in mind that you have a choice.

Request Routing¶

In the last chapter we built a very simple web application with only a single route. Here is the routing part of the “Hello World” example again:

@route('/hello')
def hello():
    return "Hello World!"

The route() decorator links an URL path to a callback function, and adds a new route to the default application. An application with just one route is kind of boring, though. Let’s add some more:

@route('/')
@route('/hello/<name>')
def greet(name='Stranger'):
    return template('Hello {{name}}, how are you?', name=name)

This example demonstrates two things: You can bind more than one route to a single callback, and you can add wildcards to URLs and access them via keyword arguments.

Dynamic Routes¶

Routes that contain wildcards are called dynamic routes (as opposed to static routes) and match more than one URL at the same time. A simple wildcard consists of a name enclosed in angle brackets (e.g. <name>) and accepts one or more characters up to the next slash (/). For example, the route /hello/<name> accepts requests for /hello/alice as well as /hello/bob, but not for /hello, /hello/ or /hello/mr/smith.

Each wildcard passes the covered part of the URL as a keyword argument to the request callback. You can use them right away and implement RESTful, nice-looking and meaningful URLs with ease. Here are some other examples along with the URLs they’d match:

@route('/wiki/<pagename>')            # matches /wiki/Learning_Python
def show_wiki_page(pagename):
    ...

@route('/<action>/<user>')            # matches /follow/defnull
def user_api(action, user):
    ...

New in version 0.10.

Filters are used to define more specific wildcards, and/or transform the covered part of the URL before it is passed to the callback. A filtered wildcard is declared as <name:filter> or <name:filter:config>. The syntax for the optional config part depends on the filter used.

The following filters are implemented by default and more may be added:

  • :int matches (signed) digits only and converts the value to integer.
  • :float similar to :int but for decimal numbers.
  • :path matches all characters including the slash character in a non-greedy way and can be used to match more than one path segment.
  • :re allows you to specify a custom regular expression in the config field. The matched value is not modified.

Let’s have a look at some practical examples:

@route('/object/<id:int>')
def callback(id):
    assert isinstance(id, int)

@route('/show/<name:re:[a-z]+>')
def callback(name):
    assert name.isalpha()

@route('/static/<path:path>')
def callback(path):
    return static_file(path, ...)

You can add your own filters as well. See Routing for details.

Changed in version 0.10.

The new rule syntax was introduced in Bottle 0.10 to simplify some common use cases, but the old syntax still works and you can find a lot of code examples still using it. The differences are best described by example:

Old Syntax New Syntax
:name <name>
:name#regexp# <name:re:regexp>
:#regexp# <:re:regexp>
:## <:re>

Try to avoid the old syntax in future projects if you can. It is not currently deprecated, but will be eventually.

HTTP Request Methods¶

The HTTP protocol defines several request methods (sometimes referred to as “verbs”) for different tasks. GET is the default for all routes with no other method specified. These routes will match GET requests only. To handle other methods such as POST, PUT or DELETE, add a method keyword argument to the route() decorator or use one of the four alternative decorators: get(), post(), put() or delete().

The POST method is commonly used for HTML form submission. This example shows how to handle a login form using POST:

from bottle import get, post, request # or route

@get('/login') # or @route('/login')
def login():
    return '''
        <form action="/login" method="post">
            Username: <input name="username" type="text" />
            Password: <input name="password" type="password" />
            <input value="Login" type="submit" />
        </form>
    '''

@post('/login') # or @route('/login', method='POST')
def do_login():
    username = request.forms.get('username')
    password = request.forms.get('password')
    if check_login(username, password):
        return "<p>Your login information was correct.</p>"
    else:
        return "<p>Login failed.</p>"

In this example the /login URL is linked to two distinct callbacks, one for GET requests and another for POST requests. The first one displays a HTML form to the user. The second callback is invoked on a form submission and checks the login credentials the user entered into the form. The use of Request.forms is further described in the Request Data section.

Special Methods: HEAD and ANY

The HEAD method is used to ask for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information about a resource without having to download the entire document. Bottle handles these requests automatically by falling back to the corresponding GET route and cutting off the request body, if present. You don’t have to specify any HEAD routes yourself.

Additionally, the non-standard ANY method works as a low priority fallback: Routes that listen to ANY will match requests regardless of their HTTP method but only if no other more specific route is defined. This is helpful for proxy-routes that redirect requests to more specific sub-applications.

To sum it up: HEAD requests fall back to GET routes and all requests fall back to ANY routes, but only if there is no matching route for the original request method. It’s as simple as that.

Routing Static Files¶

Static files such as images or CSS files are not served automatically. You have to add a route and a callback to control which files get served and where to find them:

from bottle import static_file
@route('/static/<filename>')
def server_static(filename):
    return static_file(filename, root='/path/to/your/static/files')

The static_file() function is a helper to serve files in a safe and convenient way (see Static Files). This example is limited to files directly within the /path/to/your/static/files directory because the <filename> wildcard won’t match a path with a slash in it. To serve files in subdirectories, change the wildcard to use the path filter:

@route('/static/<filepath:path>')
def server_static(filepath):
    return static_file(filepath, root='/path/to/your/static/files')

Be careful when specifying a relative root-path such as root='./static/files'. The working directory (./) and the project directory are not always the same.

Error Pages¶

If anything goes wrong, Bottle displays an informative but fairly plain error page. You can override the default for a specific HTTP status code with the error() decorator:

from bottle import error
@error(404)
def error404(error):
    return 'Nothing here, sorry'

From now on, 404 File not Found errors will display a custom error page to the user. The only parameter passed to the error-handler is an instance of HTTPError. Apart from that, an error-handler is quite similar to a regular request callback. You can read from request, write to response and return any supported data-type except for HTTPError instances.

Error handlers are used only if your application returns or raises an HTTPError exception (abort() does just that). Changing Request.status or returning HTTPResponse won’t trigger the error handler.

Generating content¶

In pure WSGI, the range of types you may return from your application is very limited. Applications must return an iterable yielding byte strings. You may return a string (because strings are iterable) but this causes most servers to transmit your content char by char. Unicode strings are not allowed at all. This is not very practical.

Bottle is much more flexible and supports a wide range of types. It even adds a Content-Length header if possible and encodes unicode automatically, so you don’t have to. What follows is a list of data types you may return from your application callbacks and a short description of how these are handled by the framework:

Dictionaries
As mentioned above, Python dictionaries (or subclasses thereof) are automatically transformed into JSON strings and returned to the browser with the Content-Type header set to application/json. This makes it easy to implement json-based APIs. Data formats other than json are supported too. See the tutorial-output-filter to learn more.
Empty Strings, False, None or other non-true values:
These produce an empty output with the Content-Length header set to 0.
Unicode strings
Unicode strings (or iterables yielding unicode strings) are automatically encoded with the codec specified in the Content-Type header (utf8 by default) and then treated as normal byte strings (see below).
Byte strings
Bottle returns strings as a whole (instead of iterating over each char) and adds a Content-Length header based on the string length. Lists of byte strings are joined first. Other iterables yielding byte strings are not joined because they may grow too big to fit into memory. The Content-Length header is not set in this case.
Instances of HTTPError or HTTPResponse
Returning these has the same effect as when raising them as an exception. In case of an HTTPError, the error handler is applied. See Error Pages for details.
File objects
Everything that has a .read() method is treated as a file or file-like object and passed to the wsgi.file_wrapper callable defined by the WSGI server framework. Some WSGI server implementations can make use of optimized system calls (sendfile) to transmit files more efficiently. In other cases this just iterates over chunks that fit into memory. Optional headers such as Content-Length or Content-Type are not set automatically. Use send_file() if possible. See Static Files for details.
Iterables and generators
You are allowed to use yield within your callbacks or return an iterable, as long as the iterable yields byte strings, unicode strings, HTTPError or HTTPResponse instances. Nested iterables are not supported, sorry. Please note that the HTTP status code and the headers are sent to the browser as soon as the iterable yields its first non-empty value. Changing these later has no effect.

The ordering of this list is significant. You may for example return a subclass of str with a read() method. It is still treated as a string instead of a file, because strings are handled first.

Changing the Default Encoding

Bottle uses the charset parameter of the Content-Type header to decide how to encode unicode strings. This header defaults to text/html; charset=UTF8 and can be changed using the Response.content_type attribute or by setting the Response.charset attribute directly. (The Response object is described in the section The Response Object.)

from bottle import response
@route('/iso')
def get_iso():
    response.charset = 'ISO-8859-15'
    return u'This will be sent with ISO-8859-15 encoding.'

@route('/latin9')
def get_latin():
    response.content_type = 'text/html; charset=latin9'
    return u'ISO-8859-15 is also known as latin9.'

In some rare cases the Python encoding names differ from the names supported by the HTTP specification. Then, you have to do both: first set the Response.content_type header (which is sent to the client unchanged) and then set the Response.charset attribute (which is used to encode unicode).

Static Files¶

You can directly return file objects, but static_file() is the recommended way to serve static files. It automatically guesses a mime-type, adds a Last-Modified header, restricts paths to a root directory for security reasons and generates appropriate error responses (403 on permission errors, 404 on missing files). It even supports the If-Modified-Since header and eventually generates a 304 Not Modified response. You can pass a custom MIME type to disable guessing.

from bottle import static_file
@route('/images/<filename:re:.*\.png>')
def send_image(filename):
    return static_file(filename, root='/path/to/image/files', mimetype='image/png')

@route('/static/<filename:path>')
def send_static(filename):
    return static_file(filename, root='/path/to/static/files')

You can raise the return value of static_file() as an exception if you really need to.

Forced Download

Most browsers try to open downloaded files if the MIME type is known and assigned to an application (e.g. PDF files). If this is not what you want, you can force a download dialog and even suggest a filename to the user:

@route('/download/<filename:path>')
def download(filename):
    return static_file(filename, root='/path/to/static/files', download=filename)

If the download parameter is just True, the original filename is used.

HTTP Errors and Redirects¶

The abort() function is a shortcut for generating HTTP error pages.

from bottle import route, abort
@route('/restricted')
def restricted():
    abort(401, "Sorry, access denied.")

To redirect a client to a different URL, you can send a 303 See Other response with the Location header set to the new URL. redirect() does that for you:

from bottle import redirect
@route('/wrong/url')
def wrong():
    redirect("/right/url")

You may provide a different HTTP status code as a second parameter.

Note

Both functions will interrupt your callback code by raising an HTTPError exception.

Other Exceptions

All exceptions other than HTTPResponse or HTTPError will result in a 500 Internal Server Error response, so they won’t crash your WSGI server. You can turn off this behavior to handle exceptions in your middleware by setting bottle.app().catchall to False.

The Response Object¶

Response metadata such as the HTTP status code, response headers and cookies are stored in an object called response up to the point where they are transmitted to the browser. You can manipulate these metadata directly or use the predefined helper methods to do so. The full API and feature list is described in the API section (see Response), but the most common use cases and features are covered here, too.

Status Code

The HTTP status code controls the behavior of the browser and defaults to 200 OK. In most scenarios you won’t need to set the Response.status attribute manually, but use the abort() helper or return an HTTPResponse instance with the appropriate status code. Any integer is allowed, but codes other than the ones defined by the HTTP specification will only confuse the browser and break standards.

Response Header

Response headers such as Cache-Control or Location are defined via Response.set_header(). This method takes two parameters, a header name and a value. The name part is case-insensitive:

@route('/wiki/<page>')
def wiki(page):
    response.set_header('Content-Language', 'en')
    ...

Most headers are unique, meaning that only one header per name is send to the client. Some special headers however are allowed to appear more than once in a response. To add an additional header, use Response.add_header() instead of Response.set_header():

response<">



gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.