Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Génération de rapports

APERTO-NOTA

Moteur de templates Jinja2

Jinja2 est un moteur de templates puissant qui permet de générer dynamiquement du contenu à partir de modèles. Il est souvent utilisé pour produire du HTML, mais peut aussi servir à générer du texte, du LaTeX, du Markdown, etc.

Installation

pip install jinja2

Exemple simple de rendu

from jinja2 import Template

template = Template("Bonjour {{ nom }} !")
message = template.render(nom="Alice")
print(message)

Exemple avec une liste

from jinja2 import Template

utilisateurs = [
    {"id": 1, "name": "Alice", "email": "alice@example.com"},
    {"id": 2, "name": "Bob", "email": "bob@example.com"},
    {"id": 3, "name": "Charlie", "email": "charlie@example.com"}
]

template_str = """
Liste des utilisateurs :
{% for u in utilisateurs %}
- {{ u.id }} - {{ u.name }} - {{ u.email }}
{% endfor %}
"""

template = Template(template_str)
output = template.render(utilisateurs=utilisateurs)
print(output)

Utilisation avec un fichier HTML

Jinja2 peut aussi charger un template HTML externe. Cela permet de séparer clairement le contenu (Python) de la présentation (HTML).

Exemple

Fichier template.html :

<!DOCTYPE html>
<html>
<head>
    <title>Utilisateurs</title>
</head>
<body>
    <h1>Liste des utilisateurs</h1>
    <ul>
    {% for u in utilisateurs %}
        <li>{{ u.id }} - {{ u.name }} - {{ u.email }}</li>
    {% endfor %}
    </ul>
</body>
</html>

Script Python :

from jinja2 import Environment, FileSystemLoader

# Chargement du template depuis un dossier
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('template.html')

# Données
utilisateurs = [
    {"id": 1, "name": "Alice", "email": "alice@example.com"},
    {"id": 2, "name": "Bob", "email": "bob@example.com"},
    {"id": 3, "name": "Charlie", "email": "charlie@example.com"}
]

# Rendu
html_output = template.render(utilisateurs=utilisateurs)

# Sauvegarde dans un fichier HTML
with open("users.html", "w", encoding="utf-8") as f:
    f.write(html_output)

Exercice

Solution to Exercise 1 #

Fichier rapport_template.html :

<!DOCTYPE html>
<html>
<head>
    <title>Rapport des commandes</title>
</head>
<body>
    <h1>Rapport des commandes</h1>
    <table border="1">
        <tr>
            <th>Numéro</th>
            <th>Client</th>
            <th>Total</th>
            <th>Statut</th>
        </tr>
        {% for commande in commandes %}
        <tr>
            <td>{{ commande.numero }}</td>
            <td>{{ commande.client }}</td>
            <td>{{ commande.total }}</td>
            <td>{{ commande.statut }}</td>
        </tr>
        {% endfor %}
    </table>
    <h2>Total général : {{ total_general }} €</h2>
</body>
</html>

Script Python :

from jinja2 import Environment, FileSystemLoader
import logging

# Configuration du logging
logging.basicConfig(filename='rapport.log', level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')

try:
    logging.info("Début du script de génération de rapport HTML.")

    # Données
    commandes = [
        {"numero": 101, "client": "Alice", "total": 149.99, "statut": "Livrée"},
        {"numero": 102, "client": "Bob", "total": 89.50, "statut": "En cours"},
        {"numero": 103, "client": "Charlie", "total": 230.00, "statut": "Annulée"}
    ]

    # Calcul du total général (hors commandes annulées)
    total_general = sum(commande['total'] for commande in commandes if commande['statut'] != 'Annulée')

    # Chargement du template
    env = Environment(loader=FileSystemLoader('.'))
    template = env.get_template('rapport_template.html')
    logging.info("Template HTML chargé avec succès.")

    # Rendu
    html_output = template.render(commandes=commandes, total_general=total_general)

    # Sauvegarde
    with open("rapport_commandes.html", "w", encoding="utf-8") as f:
        f.write(html_output)
    logging.info("Fichier HTML 'rapport_commandes.html' généré avec succès.")

except Exception as e:
    logging.error(f"Erreur lors de la génération du fichier HTML : {e}")