⌘BABAKOV.NET Let's code!
100% [light] [ru]

Python Bottle Guide (Translation) Part 3 - Routing Requests

In the previous part (Python Bottle Guide (Translation) Part 2 - Hello World) we created a simple Web application with one single route, here is the part of the code with routing from the 'Hello World' example:

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


In this example, the route() decorator binds the URL path to the called function and adds a new route.

Now let's add another route:

@route(\'/\')
@route(\'/hello/<name>\')
def greet(name=\'Незнакомец\'):
    return template(\'Здравствуй {{name}}, как дела?\', name=name)


(Don't forget to import the necessary libraries: from bottle import template)

This example demonstrates two important things at once: you can bind multiple routes to one called function, and you can add URL address templates and get access to parameters by keyword.

Dynamic Routing


Routes that contain templates (routing templates) are called dynamic and correspond to multiple URL addresses at once. A simple template consists of a name enclosed in angle brackets,

(например, <name>)

and takes one or more characters until the next slash (/). For example, the route

/hello/<name>

accepts requests for /hello/roman, as well as /hello/lena, but not for /hello, /hello/, or /hello/mr/roman.

Each template takes the corresponding part of the URL address and passes it as a keyword argument to the called function. This can be easily used and implemented for RESTful (clean links), beautiful and understandable URL addresses. Here are a few more examples of routes with corresponding URL addresses:

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

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



To accurately determine the value in the part of the URL address represented by the template and pass or convert the value to the called function, filters can be used. A template with a filter is written as follows:

<name:filter>

or

<name:filter:config>

The config part is optional and its syntax depends on the used filter.

The following filters are included by default:
: int signed integer - converts the value to an integer.
: float similar to int, but for decimal numbers.
: path matches all characters, including the slash, and can be used to match multiple path segments.
: re allows you to specify a custom regular expression in the config field.

Let's 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, ...)



HTTP Request Methods


HTTP protocol defines several methods for different tasks. The GET method is the default for all routes for which no method is explicitly defined, such routes will only match requests with the GET method. To handle other methods, such as POST, PUT, DELETE, or PATCH, you need to add the necessary method keyword to the route() decorator or use one of the five alternative decorators: get(), post(), put(), delete(), or patch().

The POST method is usually used for sending HTML forms. In the example below, you can see how data from an authorization form is processed using the POST method:

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>Вы ввели корректный логин и пароль.</p>"
    else:
        return "<p>Логин или пароль не верен.</p>"



In this example, the URL address /login is associated with two different functions: one for the GET request and the other for the POST request. The first displays an HTML form for user input. The second is called when the form is submitted and checks the user's credentials.

Special Methods: HEAD and ANY

The HEAD method is used to get a response identical to the GET request, but without the response body. This is useful for getting metadata about a resource without having to load the entire document. Bottle automatically handles such requests by addressing the corresponding GET route and truncating the response body if it exists. There is no need to describe HEAD routes individually.

In addition, the non-standard ANY method works as a fallback with low priority: routes that listen for ANY will match requests regardless of their HTTP method, but only if no more specific route is defined. This is useful for proxy routes that redirect requests to more specific subroutines.

In summary: HEAD requests are redirected to GET routes and return only metadata, and all other requests are returned to ANY routes, but only if no corresponding route is defined for the original request method.

Routing Static Files


Static files, such as images or CSS style files, are not automatically served. You need to add a route and a called function to control which files will be served and where to look for 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 helps safely and conveniently serve files. This example is limited to files directly in the /path/to/your/static/files directory, as the template

<filename>

will not match a path with a slash in it. To serve files in subdirectories, you need to change the template 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 do not always match.

Error Pages


If something goes wrong, Bottle will display an informative but quite simple error page. However, you can redefine the default value for a specific HTTP status code using the error() method:

from bottle import error
@error(404)
def error404(error):
    return \'Упс, извините страница не найдена!\'


Now errors 404 File not Found will display a custom error page. The only parameter passed to the error handler is an instance of HTTPError. In addition, the error handler is very similar to a regular request function. You can read from the request, write to the response, and return any supported data type, except for instances of HTTPError.

Error handlers are only used if your application returns or raises an HTTPError exception (abort() does this). Changing Request.status or returning an HTTPResponse will not trigger an error handler.

Continuation:
Python Bottle Guide (Translation) Part 4 - Creating Content

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.