aboutsummaryrefslogtreecommitdiff
path: root/app/app_templating.py
diff options
context:
space:
mode:
authorpacien2021-07-29 18:04:48 +0200
committerpacien2021-07-29 18:04:48 +0200
commit57ff25198a82b3f6f413440e4005f0ade8dfb8d8 (patch)
tree817c43e04b3413d773a999c1950e1af43f26c3e2 /app/app_templating.py
parentf80c19c18eb01ed7e7c6f44cc25535c14659ba20 (diff)
downloaduge_l2_rdbms_python_proto-57ff25198a82b3f6f413440e4005f0ade8dfb8d8.tar.gz
app: render and serve proper web pages
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)