From a1729d13f75eb36bd0445f50e9de7f6c00db8a27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rn-Michael=20Miehe?= Date: Tue, 31 Oct 2023 23:43:38 +0100 Subject: [PATCH] common code for helpers.list_* functions --- api/advent22_api/core/helpers.py | 35 +++++++++++++++----------------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/api/advent22_api/core/helpers.py b/api/advent22_api/core/helpers.py index 639dc07..4472cdf 100644 --- a/api/advent22_api/core/helpers.py +++ b/api/advent22_api/core/helpers.py @@ -3,7 +3,7 @@ import random import re from datetime import date, datetime, timedelta from io import BytesIO -from typing import Any, Iterable, Self, Sequence, TypeVar +from typing import Any, Awaitable, Callable, Iterable, Self, Sequence, TypeVar from fastapi.responses import StreamingResponse from PIL import Image @@ -13,6 +13,7 @@ from .dav.webdav import WebDAV T = TypeVar("T") RE_IMG = re.compile(r"\.(gif|jpe?g|tiff?|png|bmp)$", flags=re.IGNORECASE) +RE_TTF = re.compile(r"\.(ttf)$", flags=re.IGNORECASE) class Random(random.Random): @@ -80,30 +81,26 @@ def spread( return result -async def list_images_auto() -> list[str]: +def list_helper( + directory: str, + regex: re.Pattern[str], +) -> Callable[[], Awaitable[list[str]]]: """ - Finde alle Bilddateien im "automatisch"-Verzeichnis + Finde alle Dateien im Verzeichnis `dir`, passend zu `re` """ - __DIR = "/images_auto" + async def _list_helper() -> list[str]: + return [ + f"{directory}/{file}" + for file in await WebDAV.list_files(directory=directory, regex=regex) + ] - return [ - f"{__DIR}/{file}" - for file in await WebDAV.list_files(directory=__DIR, regex=RE_IMG) - ] + return _list_helper -async def list_images_manual() -> list[str]: - """ - Finde alle Bilddateien im "manuell"-Verzeichnis - """ - - __DIR = "/images_manual" - - return [ - f"{__DIR}/{file}" - for file in await WebDAV.list_files(directory=__DIR, regex=RE_IMG) - ] +list_images_auto = list_helper("/images_auto", RE_IMG) +list_images_manual = list_helper("/images_manual", RE_IMG) +list_fonts = list_helper("/files", RE_TTF) async def load_image(file_name: str) -> Image.Image: