From 4ea2b3736225e8171c74b595c06cc888a254c815 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rn-Michael=20Miehe?= Date: Fri, 14 Oct 2022 23:21:14 +0000 Subject: [PATCH] remove static "loesungswort" --- api/advent22_api/routers/_misc.py | 11 ++++++++--- api/advent22_api/routers/days.py | 9 ++++----- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/api/advent22_api/routers/_misc.py b/api/advent22_api/routers/_misc.py index 3b402e8..3947a13 100644 --- a/api/advent22_api/routers/_misc.py +++ b/api/advent22_api/routers/_misc.py @@ -1,6 +1,6 @@ import itertools import random -from typing import Sequence +from typing import Any, Sequence from ..dav_common import dav_get_file @@ -10,6 +10,10 @@ async def get_loesungswort() -> str: return fp.read().decode("utf8").strip() +async def get_rnd(bonus_salt: Any = "") -> random.Random: + loesungswort = await get_loesungswort() + return random.Random(f"{loesungswort}{bonus_salt}") + async def set_length(seq: Sequence, length: int) -> list: # `seq` unendlich wiederholen @@ -18,9 +22,10 @@ async def set_length(seq: Sequence, length: int) -> list: return list(itertools.islice(infinite, length)) -async def shuffle(seq: Sequence) -> list: +async def shuffle(seq: Sequence, rnd: random.Random | None = None) -> list: # Zufallsgenerator - rnd = random.Random(await get_loesungswort()) + if rnd is None: + rnd = await get_rnd() # Elemente mischen return rnd.sample(seq, len(seq)) diff --git a/api/advent22_api/routers/days.py b/api/advent22_api/routers/days.py index b48c9c8..3d5c838 100644 --- a/api/advent22_api/routers/days.py +++ b/api/advent22_api/routers/days.py @@ -1,5 +1,4 @@ import colorsys -import random import re # from datetime import date from io import BytesIO @@ -10,15 +9,14 @@ from PIL import ImageDraw, ImageFont from ..dav_common import dav_get_file, dav_list_files from ._image import AdventImage -from ._misc import set_length, shuffle +from ._misc import get_loesungswort, get_rnd, set_length, shuffle router = APIRouter(prefix="/days", tags=["days"]) -loesungswort = "ABCDEFGHIJKLMNOPQRSTUVWX" - @router.on_event("startup") async def startup() -> None: + loesungswort = await get_loesungswort() print(loesungswort) print("".join(await shuffle(loesungswort))) @@ -26,6 +24,7 @@ async def startup() -> None: @router.get("/letter/{index}") async def get_letter( index: int, + loesungswort: str = Depends(get_loesungswort), ) -> str: return (await shuffle(loesungswort))[index] @@ -99,7 +98,7 @@ async def get_picture_for_day( font = ImageFont.truetype("Lena.ttf", 50) # Position des Buchstaben bestimmen - rnd = random.Random(f"{loesungswort}{index}") + rnd = await get_rnd(index) xy = tuple(rnd.choices(range(30, 470), k=2)) # betroffenen Bildbereich bestimmen