-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
86 lines (67 loc) · 2.53 KB
/
main.py
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import asyncio
import datetime as dtm
import logging
import os
import zoneinfo
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path
from dotenv import load_dotenv
from jinja2 import FileSystemLoader, StrictUndefined
from pydantic import BaseModel
from akalisten.clients.polls import PollAPI
from akalisten.jinja2 import RelImportEnvironment
from akalisten.polls import PollInfo, PollVotes
load_dotenv(override=True)
ROOT = Path(__file__).parent
DUMMY_DATA = ROOT / "dummy_data.json"
LOGS = ROOT / "logs"
LOGS.mkdir(exist_ok=True)
DEBUG_MODE = os.getenv("DEBUG") is not None
handler = TimedRotatingFileHandler(
filename=LOGS / "akalisten.log", when="midnight", interval=1, backupCount=30, encoding="utf-8"
)
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.WARNING,
handlers=[handler] if not DEBUG_MODE else [logging.StreamHandler()],
)
async def get_poll_data() -> tuple[dict[int, PollInfo], dict[int, PollVotes]]:
class TempData(BaseModel):
polls: dict[int, PollInfo]
poll_votes: dict[int, PollVotes]
if DEBUG_MODE and DUMMY_DATA.exists():
tmp_data = TempData.model_validate_json(DUMMY_DATA.read_text(encoding="utf-8"))
for poll_votes in tmp_data.poll_votes.values():
poll_votes.sanitize_nos()
else:
tmp_data = TempData(polls={}, poll_votes={})
async with PollAPI() as client:
for poll in await client.get_polls_info():
if not poll.is_active_mucken_liste:
continue
votes = await client.aggregate_poll_votes(poll.id)
tmp_data.poll_votes[poll.id] = votes
tmp_data.polls[poll.id] = poll
if DEBUG_MODE:
DUMMY_DATA.write_text(tmp_data.model_dump_json(indent=2), encoding="utf-8")
return tmp_data.polls, tmp_data.poll_votes
async def main() -> None:
polls, poll_votes = await get_poll_data()
environment = RelImportEnvironment(
loader=FileSystemLoader(ROOT / Path("akalisten/templates")),
lstrip_blocks=True,
trim_blocks=True,
undefined=StrictUndefined,
)
timezone = zoneinfo.ZoneInfo("Europe/Berlin")
(ROOT / "index.html").write_text(
environment.get_template("lotsude/index.j2").render(
polls=polls, poll_votes=poll_votes, now=dtm.datetime.now(timezone)
),
encoding="utf-8",
)
if __name__ == "__main__":
try:
asyncio.run(main())
except Exception as exc:
logging.exception(exc)