aboutsummaryrefslogtreecommitdiff
path: root/app/app_templating.py
blob: 427170b704f16b364cf9997297410565abf7f086 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# UGE / L2 / Intro to relational databases / Python project prototype
# Author: Pacien TRAN-GIRARD
# Licence: EUPL-1.2

from typing import Optional, NamedTuple
from decimal import Decimal

from fastapi import Depends, Request
from fastapi.templating import Jinja2Templates

from app_sessions import UserSession, FlashMessageQueue
from app_database import db_transaction


# Load and parse Jinja HTML templates pages and fragments.
bare_templates = Jinja2Templates(directory='./templates/')


class TemplateRenderer:
    """
    Template renderer using dependency injection to populate the template
    parameters used by all pages.
    """

    def __init__(
        self,
        request: Request,
        messages: FlashMessageQueue=Depends(FlashMessageQueue),
        session: UserSession=Depends(UserSession),
    ):
        self._request = request
        self._messages = messages
        self._session = session

    def _get_user(self) -> Optional[NamedTuple]:
        if not self._session.is_logged_in():
            return None

        with db_transaction() as tx:
            return tx.fetch_account(user_id=self._session.get_user_id())

    def _shared_template_args(self) -> dict:
        return {
            'request': self._request,
            'messages': self._messages,
            'user': self._get_user(),
        }

    def __call__(self, template: str, **kwargs):
        template_args = self._shared_template_args() | kwargs
        return bare_templates.TemplateResponse(template, template_args)