Routing

The Jam.py v7 introduced routing. As Jam.py v5 is a SPA (Single Page Application), there was no need for routing. On the other hand, there was a need to implement, for example, the User registration page with Jam.py v5.

The solution for this problem was similar to creating a registration form.

As seen, the register.html file is using JavaScript AJAX code. Hence, any additional page would need a similar approach, if interacting with the database.

In Jam.py v7, the solution is to process every request in the on_request event handler and defining a response on a valid request.

This enables us to do a custom login and registration forms, where custom errors can be created. For example: “User does not exist!”, “Wrong password”, etc.

The new login.html page with the error message:

Custom Login Form

The new register.html page (no AJAX):

Registration Form

Routing code

As mentioned, the on_request is used.

The below code should exist on “Task/Server Module”. No Python logic is included below to make it simple to read:

def on_request(task, request):
        parts = request.path.strip('/').split('/')
        if not parts[0]:
            if task.logged_in(request):
                return task.serve_page('index.html')
            else:
                return task.redirect('/login.html')
        elif parts[0] == 'login.html':
                                .
                                .

        elif parts[0] == 'register.html':
                                .
                                .
                    return task.serve_page('register.html')
                                .
                                .

                    return task.redirect('/login.html')

The working example for serving robots.txt file:

def on_request(task, request):
    parts = request.path.strip('/').split('/')
    if not parts[0]:
        if task.logged_in(request):
            return task.serve_page('index.html')
        else:
            return task.redirect('/login.html')
    elif parts[0] == 'robots.txt':
        if task.logged_in(request):
            return task.serve_page('robots.txt')

The robots.txt file should exist within the application folder.

See also

serve_page

redirect

on_request