aboutsummaryrefslogtreecommitdiff
path: root/app/app_templating.py
diff options
context:
space:
mode:
Diffstat (limited to 'app/app_templating.py')
-rw-r--r--app/app_templating.py51
1 files changed, 51 insertions, 0 deletions
diff --git a/app/app_templating.py b/app/app_templating.py
new file mode 100644
index 0000000..427170b
--- /dev/null
+++ b/app/app_templating.py
@@ -0,0 +1,51 @@
1# UGE / L2 / Intro to relational databases / Python project prototype
2# Author: Pacien TRAN-GIRARD
3# Licence: EUPL-1.2
4
5from typing import Optional, NamedTuple
6from decimal import Decimal
7
8from fastapi import Depends, Request
9from fastapi.templating import Jinja2Templates
10
11from app_sessions import UserSession, FlashMessageQueue
12from app_database import db_transaction
13
14
15# Load and parse Jinja HTML templates pages and fragments.
16bare_templates = Jinja2Templates(directory='./templates/')
17
18
19class TemplateRenderer:
20 """
21 Template renderer using dependency injection to populate the template
22 parameters used by all pages.
23 """
24
25 def __init__(
26 self,
27 request: Request,
28 messages: FlashMessageQueue=Depends(FlashMessageQueue),
29 session: UserSession=Depends(UserSession),
30 ):
31 self._request = request
32 self._messages = messages
33 self._session = session
34
35 def _get_user(self) -> Optional[NamedTuple]:
36 if not self._session.is_logged_in():
37 return None
38
39 with db_transaction() as tx:
40 return tx.fetch_account(user_id=self._session.get_user_id())
41
42 def _shared_template_args(self) -> dict:
43 return {
44 'request': self._request,
45 'messages': self._messages,
46 'user': self._get_user(),
47 }
48
49 def __call__(self, template: str, **kwargs):
50 template_args = self._shared_template_args() | kwargs
51 return bare_templates.TemplateResponse(template, template_args)