Skip to content

36. Application Exercise: version 16

Image

36.1. Introduction

The URL in our application currently have the form [/action/param1/param2/…]. We would like to be able to prefix these URL. For example, with the prefix [/do], we would have URL in the form [/do/action/param1/param2/…].

36.2. The new route configuration

Image

  1. in [2], route calculation will be modified;
  2. in [1], the file [config] is modified to reflect this change;

The configuration [config] becomes the following:


def configure(config: dict) -> dict:
    # syspath configuration
    import syspath
    config['syspath'] = syspath.configure(config)
 
    # application setup
    import parameters
    config['parameters'] = parameters.configure(config)
 
    # database configuration
    import database
    config["database"] = database.configure(config)
 
    # instantiation of application layers
    import layers
    config['layers'] = layers.configure(config)
 
    # configuration MVC of the [web] layer
    config['mvc'] = {}
 
    # configuration of [web] layer controllers
    import controllers
    config['mvc'].update(controllers.configure(config))
 
    # actions ASV (Action Show View)
    import asv_actions
    config['mvc'].update(asv_actions.configure(config))
 
    # actions ADS (Action Do Something)
    import ads_actions
    config['mvc'].update(ads_actions.configure(config))
 
    # response configuration HTTP
    import responses
    config['mvc'].update(responses.configure(config))
 
    # route configuration
    import routes
    routes.configure(config)
 
    # we return the configuration
    return config
  1. lines 37–39: the [routes] module (line 38) handles route configuration (line 39);

The route file without the CSRF [configs/routes_without_csrftoken] token evolves as follows:


# dependencies
 
from flask import redirect, request, session, url_for
from flask_api import status
 
# application configuration
config = {}
 
# the front controller
def front_controller() -> tuple:
    # forward the request to the main controller
    main_controller = config['mvc']['controllers']['main-controller']
    return main_controller.execute(request, session, config)
 
# application root
def index() -> tuple:
    # redirect to /init-session/html
    return redirect(url_for("init_session", type_response="html"), status.HTTP_302_FOUND)
 
# init-session
def init_session(type_response: str) -> tuple:
    # execute the controller associated with the action
    return front_controller()
 
# authenticate-user
def authentifier_utilisateur() -> tuple:
    # execute the controller associated with the action
    return front_controller()
 
# calculate-tax
def calculer_impot() -> tuple:
    # execute the controller associated with the action
    return front_controller()
 

The file has been stripped of its routes. Only the functions associated with them remain.

The route files with tokens CSRF and [configs/routes_with_csrftoken] suffer the same fate:


# dependencies
 
from flask import redirect, request, session, url_for
from flask_api import status
from flask_wtf.csrf import generate_csrf
 
# configuration
config = {}
 
# the front controller
def front_controller() -> tuple:
    # forward the request to the main controller
    main_controller = config['mvc']['controllers']['main-controller']
    return main_controller.execute(request, session, config)
 
# application root
def index() -> tuple:
    # redirect to /init-session/html
    return redirect(url_for("init_session", type_response="html"csrf_token=generate_csrf()), status.HTTP_302_FOUND)
 
# init-session
def init_session(type_response: str, csrf_token: str) -> tuple:
    # execute the controller associated with the action
    return front_controller()
 
# authenticate-user
def authentifier_utilisateur(csrf_token: str) -> tuple:
    # execute the controller associated with the action
    return front_controller()
 

 
# init-session-without-csrftoken pour les clients json et xml
def init_session_without_csrftoken(type_response: str) -> tuple:
    # redirect to /init-session/type_response
    return redirect(url_for("init_session", type_response=type_response, csrf_token=generate_csrf()),
                    status.HTTP_302_FOUND)

The routes are calculated by the following [configs/routes] module:


from flask import Flask
 
def configure(config: dict):
    # route settings
 
    # flask application
    app = Flask(__name__, template_folder="../flask/templates", static_folder="../flask/static")
    config['app'] = app
 
    # import routes from web application
    if config['parameters']['with_csrftoken']:
        import routes_with_csrftoken as routes
    else:
        import routes_without_csrftoken as routes
 
    # inject configuration into routes
    routes.config = config
 
    # the application's URL prefix
    prefix_url = config["parameters"]["prefix_url"]
 
    # token CSRF
    with_csrftoken = config["parameters"]['with_csrftoken']
    if with_csrftoken:
        csrftoken_param = f"/<string:csrf_token>"
    else:
        csrftoken_param = ""
 
    # flask application routes
    # application root
    app.add_url_rule(f'{prefix_url}/', methods=['GET'],
                     view_func=routes.index)
 
    # init-session
    app.add_url_rule(f'{prefix_url}/init-session/<string:type_response>{csrftoken_param}', methods=['GET'],
                     view_func=routes.init_session)
 
    # init-session-without-csrftoken
    if with_csrftoken:
        app.add_url_rule(f'{prefix_url}/init-session-without-csrftoken/<string:type_response>',
                         methods=['GET'],
                         view_func=routes.init_session_without_csrftoken)
 
    # authenticate-user
    app.add_url_rule(f'{prefix_url}/authentifier-utilisateur{csrftoken_param}', methods=['POST'],
                     view_func=routes.authentifier_utilisateur)
 
    # calculate-tax
    app.add_url_rule(f'{prefix_url}/calculer-impot{csrftoken_param}', methods=['POST'],
                     view_func=routes.calculer_impot)
 
    # batch tax calculation
    app.add_url_rule(f'{prefix_url}/calculer-impots{csrftoken_param}', methods=['POST'],
                     view_func=routes.calculer_impots)
 
    # lister-simulations
    app.add_url_rule(f'{prefix_url}/lister-simulations{csrftoken_param}', methods=['GET'],
                     view_func=routes.lister_simulations)
 
    # delete-simulation
    app.add_url_rule(f'{prefix_url}/supprimer-simulation/<int:numero>{csrftoken_param}', methods=['GET'],
                     view_func=routes.supprimer_simulation)
 
    # end of session
    app.add_url_rule(f'{prefix_url}/fin-session{csrftoken_param}', methods=['GET'],
                     view_func=routes.fin_session)
 
    # display-calculation-tax
    app.add_url_rule(f'{prefix_url}/afficher-calcul-impot{csrftoken_param}', methods=['GET'],
                     view_func=routes.afficher_calcul_impot)
 
    # get-admindata
    app.add_url_rule(f'{prefix_url}/get-admindata{csrftoken_param}', methods=['GET'],
                     view_func=routes.get_admindata)
 
    # afficher-vue-calcul-impot
    app.add_url_rule(f'{prefix_url}/afficher-vue-calcul-impot{csrftoken_param}', methods=['GET'],
                     view_func=routes.afficher_vue_calcul_impot)
 
    # display-view-authentication
    app.add_url_rule(f'{prefix_url}/afficher-vue-authentification{csrftoken_param}', methods=['GET'],
                     view_func=routes.afficher_vue_authentification)
 
    # display-view-list-simulations
    app.add_url_rule(f'{prefix_url}/afficher-vue-liste-simulations{csrftoken_param}', methods=['GET'],
                     view_func=routes.afficher_vue_liste_simulations)
 
    # display-view-error_list
    app.add_url_rule(f'{prefix_url}/afficher-vue-liste-erreurs{csrftoken_param}', methods=['GET'],
                     view_func=routes.afficher_vue_liste_erreurs)
 
    # special case
    if with_csrftoken:
        # init-session-without-csrftoken pour les clients json et xml
        app.add_url_rule(f'{prefix_url}/init-session-without-csrftoken', methods=['GET'],
                         view_func=routes.init_session_without_csrftoken)
  1. lines 6–8: the Flask application is created and added to the configuration;
  2. lines 10–14: the route file appropriate for the situation is imported. Note that the imported file actually contains no routes; it contains only the functions associated with them;
  3. line 17: the functions associated with the routes need to know the application’s configuration;
  4. line 20: Note the prefix URL. This can be empty;
  5. lines 22–27: Routes with the CSRF token have an additional parameter compared to those without it. To handle this difference, we use the [csrftoken_param] variable:
    1. it contains an empty string if there is no CSRF token in the routes;
    2. it contains the string [/<string:csrf_token>] if there is a CSRF token;
  6. lines 29–96: each route in the application is associated with a function from the route file imported in lines 10–14;

36.3. The new controllers

Image

In the previous version, all controllers obtained the currently processed action as follows:


    def execute(self, request: LocalProxy, session: LocalProxy, config: dict) -> (dict, int):
        # retrieve elements from path
        params = request.path.split('/')
        action = params[1]

This code no longer works if there is a prefix, for example [/do/lister-simulations]. In this case, the action on line 3 would be [do] and would therefore be incorrect.

We modify this code as follows:


    def execute(self, request: LocalProxy, session: LocalProxy, config: dict) -> (dict, int):
        # retrieve elements from path
        prefix_url = config["parameters"]["prefix_url"]
        params = request.path[len(prefix_url):].split('/')
        action = params[1]

We do this in all controllers.

36.4. The new models

Image

In the previous version, each model class generated a model as follows:


def get_model_for_view(self, request: Request, session: LocalProxy, config: dict, résultat: dict) -> dict:
        # we encapsulate the paged data in the model
        modèle = {}
        # application status
        état = résultat["état"]
        # the model depends on the state
        
 
        # csrf token
        modèle['csrf_token'] = super().get_csrftoken(config)
 
        # possible actions from the view
        modèle['actions_possibles'] = []
 
        # we render the model
        return modèle

Now the model will have an additional key, the prefix URL:


def get_model_for_view(self, request: Request, session: LocalProxy, config: dict, résultat: dict) -> dict:
        # we encapsulate the paged data in the model
        modèle = {}
        # application status
        état = résultat["état"]
        # the model depends on the state
        
 
        # csrf token
        modèle['csrf_token'] = super().get_csrftoken(config)
 
        # possible actions from the view
        modèle['actions_possibles'] = []
    
        # URL prefix
        modèle["prefix_url"] = config["parameters"]["prefix_url"]
 
        # we render the model
        return modèle

36.5. The new fragments

Image

All fragments containing URL must be modified.

The [v-authentification] fragment


<!-- form HTML - post values with [authentifier-utilisateur] action -->
<form method="post" action="{{modèle.prefix_url}}/authentifier-utilisateur{{modèle.csrf_token}}">
 
    <!-- title -->
    <div class="alert alert-primary" role="alert">
        <h4>Veuillez vous authentifier</h4>
    </div>

 
</form>

The fragment [v-calcul-impot]


<!-- form HTML posted -->
<form method="post" action="{{modèle.prefix_url}}/calculer-impot{{modèle.csrf_token}}">
    <!-- 12-column message on blue background -->
    
 
</form>

The fragment [v-liste-simulations]



 
{% if modèle.simulations is defined and modèle.simulations|length!=0 %}

 
<!-- simulation table -->
<table class="table table-sm table-hover table-striped">
    
    <tr>
        <th scope="row">{{simulation.id}}</th>
        <td>{{simulation.marié}}</td>
        <td>{{simulation.enfants}}</td>
        <td>{{simulation.salaire}}</td>
        <td>{{simulation.impôt}}</td>
        <td>{{simulation.surcôte}}</td>
        <td>{{simulation.décôte}}</td>
        <td>{{simulation.réduction}}</td>
        <td>{{simulation.taux}}</td>
        <td><a href="{{modèle.prefix_url}}/supprimer-simulation/{{simulation.id}}{{modèle.csrf_token}}">Supprimer</a></td>
    </tr>
    {% endfor %}
    </tr>
    </tbody>
</table>
{% endif %}

The fragment [v-menu]


<!-- bootstrap menu -->
<nav class="nav flex-column">
    <!-- display a list of links HTML -->
    {% for optionMenu in modèle.optionsMenu %}
    <a class="nav-link" href="{{modèle.prefix_url}}{{optionMenu.url}}{{modèle.csrf_token}}">{{optionMenu.text}}</a>
    {% endfor %}
</nav>

36.6. The new response HTML

Image

In the previous version, the HTML response code ended with a redirect:


class HtmlResponse(InterfaceResponse):
 
    def build_http_response(self, request: LocalProxy, session: LocalProxy, config: dict, status_code: int,
                            résultat: dict) -> (Response, int):
        # the HTML response depends on the status code returned by the controller
        état = résultat["état"]
 
        
 
        # now it's time to generate the URL redirection, not forgetting the CSRF token if requested
        if config['parameters']['with_csrftoken']:
            csrf_token = f"/{generate_csrf()}"
        else:
            csrf_token = ""
 
        # redirect response
        return redirect(f"{ads['to']}{csrf_token}"), status.HTTP_302_FOUND

This code now becomes the following:


def build_http_response(self, request: LocalProxy, session: LocalProxy, config: dict, status_code: int,
                            résultat: dict) -> (Response, int):
        
 
        # now it's time to generate the URL redirection, not forgetting the CSRF token if requested
        if config['parameters']['with_csrftoken']:
            csrf_token = f"/{generate_csrf()}"
        else:
            csrf_token = ""
 
        # redirect response
        return redirect(f"{config['parameters']['prefix_url']}{ads['to']}{csrf_token}"), status.HTTP_302_FOUND

36.7. Tests

Image

Let's add the following prefix to the [parameters] configuration file:



        # token csrf
        "with_csrftoken"True,
        # bases managed MySQL (mysql), PostgreSQL (pgres)
        "databases"["mysql""pgres"],
        # application URL prefix
        # put empty string if no prefix or /prefix otherwise
        "prefix_url""/do",

Let’s launch the application and request URL [http://localhost:5000/do]; the response is as follows:

Image

  • in [1], the prefix of URL;
  • in [2], the token CSRF;

The application can also be tested using the console tests for [http-clients/09]:

Image

In the configuration files [1] and [2], the prefix of URL must be included in the server’s URL:


        "server": {
            # "urlServer": "http://127.0.0.1:5000",
            "urlServer""http://127.0.0.1:5000/do",
            "user": {
                "login""admin",
                "password""admin"
            },
            "url_services": {
                
            }
  • Line 3: The server's URL now includes the prefix from URL;

With this change, all console tests should work.