From f5015895c3e2c34744e59085d0c4a902caffee56 Mon Sep 17 00:00:00 2001 From: Daniel Schadt Date: Sat, 10 Feb 2024 18:22:03 +0100 Subject: only show & allow languages that are allowed Was a bit of an oversight to not use available_locales from the get-go. --- fietsboek/__init__.py | 6 ++++-- fietsboek/jinja2.py | 2 +- fietsboek/util.py | 26 +++++--------------------- 3 files changed, 10 insertions(+), 24 deletions(-) diff --git a/fietsboek/__init__.py b/fietsboek/__init__.py index 419e0fb..a5f0042 100644 --- a/fietsboek/__init__.py +++ b/fietsboek/__init__.py @@ -61,10 +61,12 @@ def locale_negotiator(request: Request) -> Optional[str]: if locale: return locale + installed_locales = request.config.available_locales + if cookie_locale := request.cookies.get("fietsboek_locale"): - return cookie_locale + if cookie_locale in installed_locales: + return cookie_locale - installed_locales = request.config.available_locales sentinel = object() negotiated = request.accept_language.lookup(installed_locales, default=sentinel) if negotiated is sentinel: diff --git a/fietsboek/jinja2.py b/fietsboek/jinja2.py index 8953912..cb17742 100644 --- a/fietsboek/jinja2.py +++ b/fietsboek/jinja2.py @@ -124,4 +124,4 @@ def global_list_languages(request: Request) -> list[tuple[str, str]]: :param request: The Pyramid request. :return: The available languages. """ - return util.list_locales(request.config.language_packs) + return util.list_locales(request) diff --git a/fietsboek/util.py b/fietsboek/util.py index da3d530..dcb9ab8 100644 --- a/fietsboek/util.py +++ b/fietsboek/util.py @@ -378,33 +378,17 @@ def locale_display_name(locale_name: str, locale_packages: Optional[list[str]] = return locale_name -def list_locales(locale_packages: Optional[list[str]] = None) -> list[tuple[str, str]]: +def list_locales(request: Request) -> list[tuple[str, str]]: """Lists all available locales. Returns a list of locale name and display name tuples. - :param locale_packages: Names of packages in which locale data is searched. + :param request: The Pyramid request for which to list the locales. """ - locale_packages = _locale_packages(locale_packages) locales = [] - for package in locale_packages: - locale_dir = importlib.resources.files(package) / "locale" - try: - for potential_locale in locale_dir.iterdir(): - if not potential_locale.is_dir() or not (potential_locale / "LC_MESSAGES").is_dir(): - # Just a random file/folder in the locale/ directory - continue - locale_name = potential_locale.name - try: - display_name = (potential_locale / DISPLAY_NAME_PATH).read_text( - encoding="utf-8" - ) - except FileNotFoundError: - display_name = locale_name - locales.append((locale_name, display_name)) - except FileNotFoundError: - continue - locales.sort(key=lambda locale: locale[0]) + for locale_name in request.config.available_locales: + display_name = locale_display_name(locale_name, request.config.language_packs) + locales.append((locale_name, display_name)) return locales -- cgit v1.2.3