Routing requests


Declare the routes of your application using the Fiole decorators.


def about(request):
    return "About Fiole sample application"

def home(request):
    return "Sweet"

Both route() and get() declare a route for the GET (and HEAD) methods. The other decorators are post(), put() and delete().

The route() decorator supports an extended syntax to match multiple methods to the same function:

@route('/api', methods=('GET', 'HEAD', 'POST'))
def multi(request):
    return "Received %s %s" % (request.method, request.path)

It is also available as a plain function:

def say_hi(request):
    return "Hi"

route('/welcome', methods=('GET', 'HEAD'), callback=say_hi)
route('/ciao', methods=('GET', 'HEAD'), callback=say_hi)

Dynamic routes

Two different syntaxes are supported.

Easy syntax

The simple syntax for URL pattern is like "/hello/<name>". The placeholder matches a non-empty path element (excluding "/"):

def ciao(request, name='Stranger'):
    return render_template('Hello {{name}}!', name=name)

Regex syntax

The advanced syntax is regex-based. The variables are extracted from the named groups of the regular expression: (?P<name>...). See Regular Expressions for the full syntax. The unnamed groups are ignored. The initial ^ and the final $ chars should be omitted: they are automatically added when the route is registered.

The pattern parser switches to the advanced syntax when an extension notation is detected: (?.


def call_api(request, action, params):
    if action == 'view':
        return "Params received {0}".format(params)
    raise NotFound("This action is not supported")


There’s a flexible way to define extensions for Fiole: you can register hooks which will be executed for each request. For example you can setup a database connection before each request, and release the connection after the request.

A dumb no-op hook looks like:

app = get_app()

def noop_hook(request):
    # acquire the resource
    # ...
        # pre-process the Request
        # ...
        response = yield
        # post-process the Response
        # ...
        yield response
        # release the resource

This example setup a database connection:

def hook_db(request):
    request.db = connect_db()
        # forward the response unchanged
        yield (yield)


Redirect a request:

def test_redirect(request):
    raise Redirect('/hello')

Return an error page:

def test_404(request):
    raise NotFound('Not here, sorry.')

Register a different error page:

template_404 = get_template("error404.tmpl")

def not_found(request):
    return template_404.render(request)

Send static files:

get_app().static_folder = "/path/to/public/directory"

def download(request, path):
    return send_file(request, path)

Table Of Contents

Previous topic


Next topic

Build templates

This Page